Android: How to update an UI from AsyncTask if AsyncTask is in a separate class?

后端 未结 7 2138
半阙折子戏
半阙折子戏 2020-12-02 12:33

I hate inner class.

I\'ve a main activity who launches a \'short-life\' AsyncTask.

AsyncTask is in a separate file, is not an inner class of

7条回答
  •  忘掉有多难
    2020-12-02 12:51

    Using Interface 1) Create one Interface

    public interface OnDataSendToActivity {
        public void sendData(String str);
    }
    

    2) Implements it in your Activity

    public class MainActivity extends Activity implements OnDataSendToActivity{
    
         @Override
         protected void onCreate(Bundle savedInstanceState) {
              new AsyncTest(this).execute(new String[]{"AnyData"}); // start your task
         }
    
         @Override
         public void sendData(String str) {
             // TODO Auto-generated method stub
    
         }
    
    }
    

    3) Create constructor in AsyncTask(Activity activity){} Register your Interface in AsyncTask file and call interface method as below.

    public class AsyncTest extends AsyncTask {
    
        OnDataSendToActivity dataSendToActivity;
        public AsyncTest(Activity activity){
            dataSendToActivity = (OnDataSendToActivity)activity;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            dataSendToActivity.sendData(result);
        }
    
    }
    

    Here, your OnPostExecute will call after all task done by AsyncTask and will get "result" as a parameter, returned by doInBackground(){ return "";}.

    While "dataSendToActivity.sendData(result);" it will call activity's overrided method "public void sendData(String str) {}".

    An edge case to remember: Be sure to pass this, i.e. you current activity's context to AsyncTask and not create another instance of your activity, otherwise your Activity will be destroyed and new one is created.

提交回复
热议问题