How to correctly start activity from PostExecute in Android?

后端 未结 3 1292
感动是毒
感动是毒 2020-11-28 11:42

I have an AsyncTask, that fills a custom List with parsed data from Internet.

In PostExecute I fill that List and get it ready to transfer it to a new Activity.

相关标签:
3条回答
  • 2020-11-28 12:26

    You should pass in the application context rather than a context from the local activity. I.e. use context.getApplicationContext() and save that in a local variable in your AsyncTask subsclass.

    The code might looks something like this:

    public class MyAsyncTask extends AsyncTask {
    
        Context context;
        private MyAsyncTask(Context context) {
            this.context = context.getApplicationContext();
        }
    
        @Override
        protected Object doInBackground(Object... params) {
            ...
        }
    
        @Override
        protected void onPostExecute(List<VideoDataDescription> result) {
            super.onPostExecute(result);
            MainActivity.progressDialog.dismiss();
    
            context.startActivity(new Intent(context, ResultsQueryActivity.class));
        }
    }
    

    you'd call it like this:

       new MyAsyncTask(context).execute();
    
    0 讨论(0)
  • 2020-11-28 12:31

    But its better if you start a new Intent Based on the response(result) obtained from the previous activities.

    This will eliminate the possibility of the error response from invoking the new intent.

    Example if the previous activity was supposed to return Succesfully... or Welcome to allow the new intent to start, the i could check it out in this way

      protected void onPostExecute(String result) {
           if (result.equals("Succesfully...")){
               context.startActivity(new Intent(context, Login_Activity.class));
               Toast.makeText(context, result, Toast.LENGTH_LONG).show();
    
    
           }else  if (result.contains("Welcome")){
               context.startActivity(new Intent(context, MainActivity.class));
           }else {
               Toast.makeText(context,result,Toast.LENGTH_LONG).show();
           }
    
        }
    
    0 讨论(0)
  • 2020-11-28 12:47

    I tried this just now ... it works in PostExecute Method!!!

    Intent intent_name = new Intent();
    intent_name.setClass(getApplicationContext(),DestinationClassName.class);
    startActivity(intent_name);
    
    0 讨论(0)
提交回复
热议问题