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?
Asked
Active
Viewed 1,166 times
1
-
Why would you want to reCreate activity? why not just simply set the data came from service – Abdul Kawee May 02 '17 at 07:55
-
You may use `EventBus` to update the activity thread after `AsyncTask` finished. – Zarul Izham May 02 '17 at 07:57
-
Service just post data and returns 0/1 . I dont have access of controls to set data in that class. – Mohammad Rashid May 02 '17 at 07:58
-
@ZarulIzham okay let me try – Mohammad Rashid May 02 '17 at 07:59
-
on the basis of returns 0/1 call function which reset your data for activity – Swapnil Kshirsagar May 02 '17 at 08:02
2 Answers
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