How to Retrieve the Data from Asynctasks Doinbackground()

How do I retrieve the data from AsyncTasks doInBackground()?

The only way to do this is using a CallBack. You can do something like this:

new CallServiceTask(this).execute(request, url);

Then in your CallServiceTask add a local class variable and call a method from that class in your onPostExecute:

private class CallServiceTask extends AsyncTask<Object, Void, Object[]>
{
RestClient caller;

CallServiceTask(RestClient caller) {
this.caller = caller;
}

protected Object[] doInBackground(Object... params)
{
HttpUriRequest req = (HttpUriRequest) params[0];
String url = (String) params[1];
return executeRequest(req, url);
}

protected onPostExecute(Object result) {
caller.onBackgroundTaskCompleted(result);
}
}

Then simply use the Object as you like in the onBackgroundTaskCompleted() method in your RestClient class.

A more elegant and extendible solution would be to use interfaces. For an example implementation see this library. I've just started it but it has an example of what you want.

How to get data from AsyncTask in android?

Just pass your ImageView to AsyncTask via constructor and then set image in onPostExecute like this:

ImageAsyncTask task = new ImageAsyncTask(myImageView);

private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView img;

ImageAsyncTask(Imageview img){
this.img = img;
}

...

protected void onPostExecute(Bitmap data) {
this.img.setImageBitmap(data);

}

How to fetch data out of AsyncTask class in android?

After doInBackground() your return will be forwarded to onPostExecute().

To use it in your activity refer this link : How to use Async result in UIThread

Retrieving return statement from doInBackground method in AsyncTask?

Yes we can retrieve/catch the return statement from doInBackground() in onPostExecute() if write AsyncTask's class statement properly.

AsyncTask is a generic class that accepts three class type (non-primitive) parameters. Try below code to understand and get returned value from doInBackground() method.

I am expecting your Evaluate class' getScore() method's return type is int.

public class EvaluateTask extends AsyncTask<Void,Void,Integer> {

ProgressDialog progress = new ProgressDialog(context);

@Override
protected void onPreExecute() {

progress.setMessage("Analysing");
progress.setIndeterminate(true);
progress.show();
}

@Override
protected Integer doInBackground(Void... params) {
Evaluate evaluate = new Evaluate(db); //Evaluate class object
return evaluate.getScore();
}

@Override
protected void onPostExecute(Integer finalScore) {

// in this method, parameter "finalScore" is the returned value from doInBackground() method, that you can use now.
super.onPostExecute(finalScore);
progress.dismiss();
Intent i = new Intent(googleAct.this, result.class);
startActivity(i);

//I am considering you were expecting below finalScore as the returned value from doInBackground() method.
//Now there should not be an error.
i.putExtra("score", finalScore);
}
}

Return data from AsyncTask Android

postExecute() can't return a value because who or what would it return to? Your original method that invoked the AsyncTask is gone because your AsyncTask is running in the background. It's asynchronous meaning when AsyncTask.execute() returns it's still running in the background, and hence postExecute() can't return a value because there's nothing to return it to.

Instead your AsyncTask needs a reference back to your Activity or some other object so it can post your values back to it. In your code the lines after you call execute() can't be there because your task hasn't finished. Instead you should create a method called updateSymbol( currentPrice, percentChange), move all that code below execute() in there, and in your AsyncTask you should pass a reference to the Activity. Then call updateSymbol( currentPrice, percentChange ) from the onPostExecute() method.

But, be careful if you have a reference back to an Activity it can be destroyed while your doInBackground() is running, and when postExecute() runs it should just drop the results or not attempt to update the UI. For example, the user rotates their phone causing the Activity to be destroyed. I find it best to hold a reference to the AsyncTask in the activity so it can cancel() it if the Activity is destroyed. You can call AsyncTask.cancel() then check if your task was canceled like:

public void postExecute( String result ) {
if( !isCanceled() ) {
// do your updating here
activity.setSymbol( result );
}
}

It's really easy to create a base class for all Activities so you can easily keep track of AsyncTasks running:

public class BaseActivity extends Activity {

List<AsyncTask> runningTasks;

public void onStop() {
for( AsyncTask task : runningTasks ) {
task.cancel(true);
}
}

public AsyncTask start( AsyncTask task ) {
runningTasks.add( task );
return task;
}

public void done( AsyncTask task ) {
runningTasks.remove( task );
}
}

Some quick pointers. You don't need execute( new String[] { "blah" + blah } ). Varargs in Java allow you to do this. execute( "blah" + blah ). You also are catching exceptions and continuing without really handling them. It will be hard when something really happens because your app catches them, and just continues as if nothing happened. If you get an error you might want to provide some feedback to the user and stop trying to execute that process. Stop, show an error to the user, and let them do the next thing. Move the catch blocks to the bottom of the methods.

Return multiple values from AsyncTask/doInBackground and use it in other method

FOG

Simply implement onPostExecute inside your AsyncTask class :)

for example :

@Override
protected void onPostExecute(String makeValue) {
// remember this method gets called on main thread
letsCallFogsMethod(makeValue); //call your method and pass the make value here :)
}

Thats it buddy :)
Now how come this onPostExecute is getting any value???
You have to return it from doInBackground method dude :)

like

@Override
protected String doInBackground(String... params) {
//after all bra bla simply say
return obj.getMake();
}

Do you notice any change in your doInBackground signature buddy?? Yeah I changed from Void to String :)

By writing String you are informing that when you are done executing doInBackground you will return a string to onPostExecute :)

So if I write as it is in the answer will it work ?? Nope.
Given that you have specified Void in your doInBackground your Async task signature might look something like

private class FogsAsyncTask extends AsyncTask<bla,blah,Void> {

Can you see the last Void??? :) But now you have chnaged doInBackground isn't it so update the AsyncTask signature as well :)

private class FogsAsyncTask extends AsyncTask<bla,blah,String> {

Now it should work fine :) Happy coding buddy :) Hope my answer helped you :)

Return data from AsyncTask class

The key for me was to create a class called URLWithParams or something because AsyncTask will allow only 1 type to be sent IN, and I needed both the URL and the params for the HTTP request.

public class URLWithParams {

public String url;
public List<NameValuePair> nameValuePairs;

public URLWithParams()
{
nameValuePairs = new ArrayList<NameValuePair>();
}
}

and then I send it to a JSONClient:

public class JSONClient extends AsyncTask<URLWithParams, Void, String> {
private final static String TAG = "JSONClient";

ProgressDialog progressDialog ;
GetJSONListener getJSONListener;
public JSONClient(GetJSONListener listener){
this.getJSONListener = listener;
}

@Override
protected String doInBackground(URLWithParams... urls) {
return connect(urls[0].url, urls[0].nameValuePairs);
}

public static String connect(String url, List<NameValuePair> pairs)
{
HttpClient httpclient = new DefaultHttpClient();

if(url == null)
{
Log.d(TAG, "want to connect, but url is null");
}
else
{
Log.d(TAG, "starting connect with url " + url);
}

if(pairs == null)
{
Log.d(TAG, "want to connect, though pairs is null");
}
else
{
Log.d(TAG, "starting connect with this many pairs: " + pairs.size());
for(NameValuePair dog : pairs)
{
Log.d(TAG, "example: " + dog.toString());
}
}

// Execute the request
HttpResponse response;
try {
// Prepare a request object
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httpPost);
// Examine the response status
Log.i(TAG,response.getStatusLine().toString());

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
return json;

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(String json ) {
getJSONListener.onRemoteCallComplete(json);
}

public interface GetJSONListener {
public void onRemoteCallComplete(String jsonFromNet);
}

}

Then call it from my main class like this

public class BookCatalog implements GetJSONListener {
private final String TAG = this.getClass().getSimpleName();

private String catalog_url = "URL";

private void getCatalogFromServer() {

URLWithParams mURLWithParams = new URLWithParams();
mURLWithParams.url = catalog_url;

try {
JSONClient asyncPoster = new JSONClient(this);
asyncPoster.execute(mURLWithParams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void onRemoteCallComplete(String jsonBookCatalogList) {

Log.d(TAG, "received json catalog:");
Log.d(TAG, jsonBookCatalogList);
JSONObject bookCatalogResult;
try {
bookCatalogResult = (JSONObject) new JSONTokener(jsonBookCatalogList).nextValue();
JSONArray books = bookCatalogResult.getJSONArray("books");

if(books != null) {
ArrayList<String> newBookOrdering = new ArrayList<String>();
int num_books = books.length();
BookCatalogEntry temp;

DebugLog.d(TAG, "apparently we found " + Integer.toString(num_books) + " books.");
for(int book_id = 0; book_id < num_books; book_id++) {
JSONObject book = books.getJSONObject(book_id);
String title = book.getString("title");
int version = book.getInt("price");
}
}

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

}

}

how to get the return value from my doInBackground task?

First, declare this asynctask class:

class MyTask extends AsyncTask<String,Void,Bitmap>{

@Override
protected Bitmap doInBackground(String... strings) {
String myString = Params[0];
try {
URL url = new URL(myString);
Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}

@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imgDisplay.setImageBitmap(bitmap);
}
}

Your zoomActivity changes to:

public class ZoomActivity  extends Activity {
ImageView imgDisplay;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_zoom);

Intent intent = getIntent();
String url2 = intent.getStringExtra("image");

Button btnClose;

imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);

//call asynctask
new MyTask().execute(url2);

btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ZoomActivity.this.finish();
}
});

}

hope this works



Related Topics



Leave a reply



Submit