Return data from AsyncTask Android

前端 未结 3 684
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 04:09

I tried to refer similar question on SO, but didn\'t got any help.

In my android app, I\'m planning to implement Recent Quote the user has visited i.e. similar to r

3条回答
  •  迷失自我
    2021-01-05 05:01

    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 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.

提交回复
热议问题