How to start an Activity from AsyncTask? - java

I've build an AsyncTask and want to start another Activity when it ends (onPostExecute) but it won't work and I can't find the problem. Maybe there is a problem with String, String, String ?
Here is my code:
public class StartSearch extends AsyncTask<String, String, String> {
private Activity activity;
#Override
protected String doInBackground(String... strings) {
StringBuilder sb = new StringBuilder();
String http = "https://list-creater-service.herokuapp.com/api/v1/search";
HttpURLConnection urlConnection = null;
JSONObject json = null;
HttpResponse response = null;
try {
//connect to server
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "list-creater-service.herokuapp.com");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("gamemode", gametype);
jsonParam.put("country", selCountry);
jsonParam.put("min_size", minSize);
jsonParam.put("max_size", maxSize);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String jsonS = sb.toString();
JSONArray jsonArray = new JSONArray(jsonS);
int length = jsonArray.length();
String[] names = new String[length];
for (int i = 0; i < length; i++) {
JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
ArrayList serverList = new ArrayList();
serverList.add(jsonObject.getString("name"));
serverData = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = serverData.edit();
Set<String> set = new HashSet<String>();
set.addAll(serverList);
editor.putStringSet("name", set);
editor.commit();
System.out.println(jsonObject.getString("name"));
names[i] = jsonObject.getString("name");
}
//String name = jsonObject.getString("name");
System.out.println("" + sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
activity.startActivity(new Intent(activity, ServerIndex.class));
}
}
Need some help!
Thx :)

You have Activity activity declared , but you have not assigned your current activity context to it . Assign the current activity context to it.
Like
activity=currentContext;

You should use runOnUIThread in your onPostExecute
runOnUiThread(new Runnable() {
public void run() {
activity.startActivity(new Intent(activity, ServerIndex.class));
}});
And as Raghunandan said, activity is not initialized. You can access the startActivity method from your StartSearch class by using
SomeActivity.this.startActivity (SomeActivity has to be initialized)
And since onPostExecute runs on the UI thread, you may or may not call runOnUIThread.

Related

Display a toast in Async

So I am trying to display a toast if the link that provided in "EditText" is equal to a specific link.
Else the code keep runing until result.
Thats how I tried to do(Its not detecting the link):
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","Error!");
}
My main code,if you need anything else from the code just tell me and I will upload:
public class DownloadTask extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(final String... urls) {
Log.e("URL", "Loading url = " + urls[0]);
StringBuilder result = new StringBuilder();
if (urls[0].equals ("http://api.openweathermap.org/data/2.5/weather?q=null&appid=8e19904c6a1db15924eef5084a978de7"))
{
Log.e("Test","DSADSADASDASDAS");
}
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
} catch (MalformedURLException e) {
result.append("Error: MalformedURLException");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
#SuppressLint("SetTextI18n")
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.e("JSON data",""+weatherInfo);
Toast.makeText(MainActivity.this, mCityName +" has been loaded", Toast.LENGTH_SHORT).show();
JSONArray jArray = new JSONArray(weatherInfo);
for(int i = 0; 0 < jArray.length(); i++){
JSONObject partJson = jArray.getJSONObject(i);
mMain.setText("The Weather in " + mCityName + " is: " + partJson.getString("main"));
mDescription.setText("And " + partJson.getString("description"));
mMain.setVisibility(View.VISIBLE);
mDescription.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you !
To show a Toast from a background thread you need to call it inside runOnUIThread like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(this, "URL is the same", Toast.LENGTH_SHORT).show();
}
});
This is assuming your AsincTask is inside an activity class.
runOnUIThread is a method of Activity class, and you need a Context to show the Toast.
If your AsyncTask is in a separate class, you will need to provide an Activity as a parameter, or use an Intent to communicate with an Activity.

Value <html> of type java.lang.String cannot be converted to JSONObject (openweather API)

Here's my code :
public class DownloadTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("main",jsonPart.getString("main"));
Log.i("description",jsonPart.getString("description"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1");
}
This error shows up. It says Value of type java.lang.String cannot be converted to JSONObject. But I saw the same code worked for an instructor in Udemy.I don't understand why it doesn't work for me. How do I solve this?
What changes do I need to make in my code?
weatherInfo must be JSONArray, not String
And then get your String with index 0
JSONArray jsonArray = jsonObject.getJSONArray("weather");
JSONObject jsonWeather = jsonArray.getJSONObject(0);

android how to make ListView refresh every 5 sec

I have ListView which have data . Data come from server and I want the ListView to update after every 5 sec. How to do this? I am new to android development. Please help me. Here is my code..
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String data = c.getString(TAG_DATA);
final String dataaaa = rcdata.getText().toString().trim();
HashMap<String, String> user_data = new HashMap<String, String>();
user_data.put(TAG_DATA, data);
personList.add(user_data);
}
ListAdapter adapter = new SimpleAdapter(
DataSendActivity.this, personList, R.layout.layout_chat,
new String[]{TAG_DATA},
new int[]{R.id.data}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
also tried this onCreate
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 5000 );
}
}, 5000 );
i get data with this method
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
//String recID = ;
//String userID = email;
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HashMap<String, String> user = db.getUserDetails();
//String name = user.get("name");
// Semail = user.get("email");
String semail = user.get("email");
final String remail = rremail;
HttpPost httppost = new HttpPost("http://samplechatapp.gear.host/myphpfile.php?sender_email="+semail+"&reciver_email="+remail+"&fatch_server_data=true");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
Log.i("","processing entity");
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.i("",line);
}
result = sb.toString();
Log.i("",result);
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
but when i open the listview app crash please help me i am very new in android
You should call the api after you get the response from the first api call . You can notifyDataSetChanged() post that .
Call notifyDataSetChanged() whenever there is change in data.
Moreover avoid using ListView instead of that start using RecyclerView.

Android app can not connect to localhost server

I've created Database in my localhost, and want parse data from it with android app.I Create server with NodeJS and it works i can see the Database in browser, but my android app can't connect with this localhost server.
Here is my Java code.
public class MainActivity extends AppCompatActivity {
protected TextView tvData;
public static ArrayList<String> titleList = new ArrayList<String>();
private static ArrayAdapter<String> adapter;
private static ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.tvJsonItem);
// adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listView1, titleList);
// lv = (ListView) findViewById(R.id.listView1);
new JSONTask().execute("http://10.0.2.2:3000/api/people");
}
public class JSONTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
int statusCode = 0;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
connection.connect(); //connect to server
statusCode = connection.getResponseCode();
if (statusCode == 200) {
System.out.println("Server responded with code: " + statusCode);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("people");
StringBuffer finalBufferdData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObj = parentArray.getJSONObject(i);
String peopleName = finalObj.getString("name");
Integer age = finalObj.getInt("age");
finalBufferdData.append(peopleName + "-->" + age + "\n");
Log.i("Hakob_log",peopleName + "-->" + age + "\n");
}
return finalBufferdData.toString(); //pases result to POstExecute
}else{
Log.i("Hakob_log","Error");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
finally {
if(connection !=null) {
connection.disconnect();
}
try {
if(reader !=null) {
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
}
I thnk something wrong with this line
new JSONTask().execute("http://localhost:3000/api/people");
Thanks
Use the IP-address of the computer that you are referring to as localhost instead, this should solve your problem e.g.:
new JSONTask().execute("http://10.0.0.100:3000/api/people");

How to pass data into string where the string will be access in another class?

I have been intending to pass co.user_id to public static String USER_ID, so that the data in string user_id can be sent to another class from the onPostExecute function. However, from the another class i get null value, which means the value didnt sent to that class. How should i store my value in string so that the value can also be access in another class?
public class connect3 extends AsyncTask<String, Void, String> {
View view;
Activity activity;
public static String USER_ID = " ";
public connect3(Activity activity, View v) {
this.activity = activity;
view = v;
}
String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
protected String doInBackground(String... arg0) {
String ipAddress = "http://192.168.1.3/apexStore2/";
try {
URL url = new URL(ipAddress +"receipts.php");
String urlParameters =
URLEncoder.encode("user_name", "UTF-8") + "=" +
URLEncoder.encode(arg0[0], "UTF-8") + "&" +
URLEncoder.encode("user_id", "UTF-8") + "=" +
URLEncoder.encode("???", "UTF-8");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
//System.out.println(response.toString());
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("results");
for(int i = 0; i < uniObject.length(); i++) {
ContactReceipt co = new ContactReceipt();
JSONObject rowObject = uniObject.getJSONObject(i);
//EventObject co = new EventObject();
co.user_id = rowObject.getString("user_id");
USER_ID = co.user_id;
System.out.println("hi1" + co.user_id);
}
//To further break down JSON
//JSONObject oneObject = mainObject.getJSONObject("1");
//String id = oneObject.getJSONObject("id");
try{
}
finally{
connection.disconnect();
}
} catch (Exception e){
System.out.println(e.toString());
}
return USER_ID;
//return "";
}
protected void onPreExecute(){
}
#Override
protected void onPostExecute(String result){
// receipt1.user_id = user_id;
// String search = USER_ID;
// Intent intent = new Intent(activity.getApplication(),receipt1.class);
//intent.putExtra(USER_ID, search);
//activity.startActivity(intent);
Intent intent = new Intent(activity.getApplication(),receipt1.class);
intent.putExtra("USER_ID", result);
activity.startActivity(intent);
}
}
This is how i call the value in another class.
Intent intent = getIntent();
String cats = intent.getStringExtra("USER_ID");
Since there are more than one UserIds this is how you should pass it to your activity see below complete code:
public class Connect3 extends AsyncTask<String, Void, List<String>> {
View view;
Activity activity;
public static String USER_ID = "yourpackagename.USER_ID";
private List<String> listUserIds;
public Connect3(Activity activity, View v) {
this.activity = activity;
view = v;
}
String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
protected List<String> doInBackground(String... arg0) {
String ipAddress = "http://192.168.1.3/apexStore2/";
try {
URL url = new URL(ipAddress +"receipts.php");
String urlParameters =
URLEncoder.encode("user_name", "UTF-8") + "=" +
URLEncoder.encode(arg0[0], "UTF-8") + "&" +
URLEncoder.encode("user_id", "UTF-8") + "=" +
URLEncoder.encode("???", "UTF-8");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
//System.out.println(response.toString());
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
if(uniObject != null && uniObject.length() > 0) {
listUserIds = new ArrayList<>(uniObject.length());
for (int i = 0; i < uniObject.length(); i++) {
ContactReceipt co = new ContactReceipt();
JSONObject rowObject = uniObject.getJSONObject(i);
//EventObject co = new EventObject();
co.user_id = rowObject.getString("user_id");
System.out.println("hi1" + co.user_id);
listUserIds.add(co.user_id);
}
}
connection.disconnect();
} catch (Exception e){
System.out.println(e.toString());
}
return listUserIds;
}
protected void onPreExecute(){
}
#Override
protected void onPostExecute(List<String> result){
// receipt1.user_id = user_id;
Intent intent = new Intent(activity.getApplication(),receipt1.class);
if(result != null){
intent.putStringArrayListExtra(USER_ID, (ArrayList<String>) result);
}
activity.startActivity(intent);
}
}
And you will get it like this in your Activity class
if(getIntent() != null){
ArrayList<String> listUserIds = getIntent().getStringArrayListExtra(Connect3.USER_ID);
}
just check before pass the value
Intent intent = new Intent(activity.getApplication(),receipt1.class);
if( !result.equalsIgnoreCase("") && search !=null ){
intent.putExtra("USER_ID", result);
} else{
intent.putExtra("USER_ID", "result is null or empty");
}
and try to get value like this
Intent intent = getIntent();
if(intent !=null){
String cats = intent.getStringExtra("USER_ID");
Log.e("value",cats);
// if cats prints "result is null or empty" that means problem inside your doinback.....
}

Categories