Properly Using Asynctask Get()

Properly Using AsyncTask get()

When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.

Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

Difference between using AsyncTask.get() and onPostExecute()

If you call AsyncTask.get() and the task is not completed, then current thread will wait (and can be interrupted).

You right, calling this method in UI thread makes AsyncTask useless. But you can call it in another thread which need result of this task for further execution.

Android: AsyncTask to make an HTTP GET Request?

Yes you are right, Asynctask is used for short running task such as connection to the network. Also it is used for background task so that you wont block you UI thread or getting exception because you cant do network connection in your UI/Main thread.

example:

class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected Boolean doInBackground(String... urls) {
try {

//------------------>>
HttpGet httppost = new HttpGet("YOU URLS TO JSON");
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);

// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();

if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);

JSONObject jsono = new JSONObject(data);

return true;
}

} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {

e.printStackTrace();
}
return false;
}

protected void onPostExecute(Boolean result) {

}

How to use AsyncTask

FAQs and general explaination of the usage of AsyncTask

=> Where should I do network operations? Where should I return my aquired values?

In general, you should do Network Operations in a Seperate Thread -> doInBackground(); since you do not want your UI to freeze when a Network Operation takes its time. So you should connect to your Service or .php script or wherever you get the Data from inside the doInBackground() method. Then you could also parse the data there and return the parsed data from the doInBackground() method by specifying the return type of doInBackground() to your desires, more about that down there. The onPostExecute() method will then receive your returned values from doInBackground() and represent them using the UI.

=> AsyncTask< String, Integer, Long> ==> How does this work?

In general, the AsyncTask class looks like this, which is nothing more than a generic class with 3 different generic types:

AsyncTask<Params, Progress, Result>

You can specify the type of Parameter the AsyncTask takes, the Type of the Progress indicator and the type of the result (the return type
of doInBackGround()).

Here is an Example of an AsyncTask looking like this:

AsyncTask<String, Integer, Long>

We have type String for the Parameters, Type Integer for the Progress and Type Long for the Result (return type of doInBackground()). You can use any type you want for Params, Progress and Result.

private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {

// these Strings / or String are / is the parameters of the task, that can be handed over via the excecute(params) method of AsyncTask
protected Long doInBackground(String... params) {

String param1 = params[0];
String param2 = params[1];
// and so on...
// do something with the parameters...
// be careful, this can easily result in a ArrayIndexOutOfBounds exception
// if you try to access more parameters than you handed over

long someLong;
int someInt;

// do something here with params
// the params could for example contain an url and you could download stuff using this url here

// the Integer variable is used for progress
publishProgress(someInt);

// once the data is downloaded (for example JSON data)
// parse the data and return it to the onPostExecute() method
// in this example the return data is simply a long value
// this could also be a list of your custom-objects, ...
return someLong;
}

// this is called whenever you call puhlishProgress(Integer), for example when updating a progressbar when downloading stuff
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}

// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(Long result) {
// do something with the result, for example display the received Data in a ListView
// in this case, "result" would contain the "someLong" variable returned by doInBackground();
}
}

=> How to use AsyncTask? How can I "call" it? How can I "execute" it?

In this case, the AsyncTask takes a String or String Array as a Parameter which will look like this once the AsyncTask is called: (The specified parameter is used in the execute(param) method of AsyncTask).

new DownloadFilesTask().execute("Somestring"); // some String as param

Be aware, that this call does not have a return value, the only return value you should use is the one returned from doInBackground(). Use the onPostExecute() method do make use of the returned value.

Also be careful with this line of code: (this execution will actually have a return value)

long myLong = new DownloadFilesTask().execute("somestring").get();

The .get() call causes the UI thread to be blocked (so the UI freezes if the operation takes longer than a few millisecons) while the AsyncTask is executing, because the execution does not take place in a separate thread. If you remove the call to .get() it will perform asynchronously.

=> What does this notation "execute(String... params)" mean?

This is a method with a so called "varargs" (variable arguments) parameter. To keep it simple, I will just say that it means that the actual number of values you can pass on to the method via this parameter is not specified, and any amount of values you hand to the method will be treated as an array inside the method. So this call could for example look like this:

execute("param1");

but it could however also look like this:

execute("param1", "param2");

or even more parameters. Assuming we are still talking about AsyncTask, the parameters can be accessed in this way in the doInBackground(String... params) method:

 protected Long doInBackground(String... params) {

String str1 = params[0];
String str2 = params[1]; // be careful here, you can easily get an ArrayOutOfBoundsException

// do other stuff
}

You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html

Also take a look at this AsyncTask example: https://stackoverflow.com/a/9671602/1590502

Android AsyncTask get result after finsih execute

You don't need a class field for the result. The AsyncTask<Params, Progress, Result> delivers everything you need.

So you want to have a String back from the Task. In order to accomplish that you have to change the Result to String. Basically like this:

public class MyClass extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... arg0) {
/* do background stuff to get the String */
return string; // the one you got from somewhere
}
}

You also have to wait for the computation by calling the method get().

String response = new MyClass().execute().get();
Toast.makeText(getApplicationContext(), "response = " + response, Toast.LENGTH_LONG).show();

Read more about AsyncTask#get here

How to properly use Intent and Uri data with AsyncTask

Why are you trying to do this approach using an intent?
From what i understand you want to start an AynTask and pass back the result to the main activty, isn't it? To achieve this you should use and interface to implement the CallBack.

public interface I_CallBackTask {

public void getResultFromAsynTask(String result);

}

private class DownloadAsyncTask extends AsyncTask<Uri, Void, String>{

private Uri mUri;
public I_CallBackTask callback;

public DownloadAsyncTask(Uri uri) {

this.mUri = uri;
}

@Override
protected void onPreExecute() {

Toast.makeText(DownloadActivity.this, "Beginning download...", Toast.LENGTH_SHORT).show();
};

@Override
protected String doInBackground(Uri... params) {

//Do your background code for download here

//return the result of your download: if is an image it could be byte[], ...

return resultfrombackground;
}
//result same type as resultfrombackground

protected void onPostExecute(String result) {

callback.getResultFromAsynTask(result);

};
}

//your main activity

public YourActivity implements CallBackTask{
// your Activity

//your code .....

//On your main activity start the asyntask and pass your uri in the parameter
DownloadAsyncTask asyntask = new DownloadAsyncTask(yourUri);
asyncTask.execute();
asyncTask.callback = this;

@Override
public void getResultFromAsynTask(String result){
// do what you need with the result and start the new activity
}

}

How to properly use AsyncTask on Android?

to check if the internet connection is available, you can do this:

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
//return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You can't call

Boolean internetConnection;
internetConnection = new CheckConnectionTask().execute();

the return value of excute() is not what you want. If you want use asyntask you can set a boolean variable in onPostExecute(...) :

private boolean isConnect = false;
private class CheckConnectionTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
try {
InetAddress ipAddr = InetAddress.getByName("https://www.google.com");

if (!ipAddr.isReachable(10000)) {
return false;
} else {
return true;
}

} catch (Exception e) {
Log.e("exception", e.toString());
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(aVoid);
isConnect = result;
}
}

But, I never use this approach to get status of internet connection, beacause I must run this asyntask before everything to get exact status.

How to use AsyncTask correctly in Android

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;

public class AsyncExample extends Activity{

private String url="http://www.google.co.in";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();

new AsyncCaller().execute();

}

private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

@Override
protected void onPreExecute() {
super.onPreExecute();

//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.show();
}
@Override
protected Void doInBackground(Void... params) {

//this method will be running on background thread so don't update UI frome here
//do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

//this method will be running on UI thread

pdLoading.dismiss();
}

}
}


Related Topics



Leave a reply



Submit