1

I have an activity in android application and from that I am calling a method of an AsyncTask class which is calling a webservice. I want to reset/reload my activity on the basis of the result i get from that method. How can I reset my activity from that class?

Mohammad Rashid
  • 138
  • 3
  • 16

2 Answers2

2

You can try the following

Pass calling Activity context to your AsyncTask in constructor and save it in a variable Context context.

Then in your PostExecute method of AsyncTask, write following lines :

        Intent targetIntent = new Intent(context, TargetActivity.class);
            // Add your data to intent
        targetIntent.putExtra("intent_extra_key", "intent_extra_value");
        context.startActivity(targetIntent);
        ((Activity) context).finish();

Revert back for any issue.

Aashish Aadarsh
  • 491
  • 5
  • 7
0

Example:

Note: Remove the comment and delete or use comment for startActivity(i); in onPostExecute(Boolean aBoolean) if you want to test code example below without changing it.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new LoadFromWebAsyncTask(this).execute();
}


private class LoadFromWebAsyncTask extends AsyncTask<Void, Void, Boolean> {

    MainActivity activity;

    LoadFromWebAsyncTask(MainActivity activity) {
        this.activity = activity;
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        return true;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);

        activity.finish();
        Intent i = new Intent(MainActivity.this, MainActivity.class);
        startActivity(i);

       /* final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                activity.finish();
                Intent i = new Intent(MainActivity.this, MainActivity.class);
                startActivity(i);
            }
        }, 5*1000);*/

    }
}
}
Mukesh M
  • 2,242
  • 6
  • 28
  • 41