Skip to content Skip to sidebar Skip to footer

How To Prevent Activity To Reload On Back Action

I have app that connects to internet to get data. I can access data multi-level. So let say I start at level 3 and on level 4 I decide to go back, whenever I press back the previo

Solution 1:

Move the data loading code to the single-exec event: onStart or

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState == null) {
         // here
    }
}

Solution 2:

You have a lot of options here. The simpler one is to avoid stopping your activity when you switch to another one. When you go to level 4 by means of startActivity(), your onPause() is called on the level 3 activity but it continues living in the background. Then when you come back from 3, onResume() is called. So as long as you don't load data on resume nor finish() your level 3 activity, you should be fine. If the system happens to be very short on resources then level 3 activity might be killed (though this is very rare) and restarted when you get back to it, but if it happens it means the system needed memory for something important and it's probably fine to reload.

Now, there are other ways. It's usually much better to do it as I described above, but if for some reason you want to finish your level 3 activity, Here are your options. As it has been noted, you may elect to dump your data somewhere. The saved instance state is an option - though if it's heavy data, more than a few kilobytes, it's not recommended. The idea is, you save your data in onSaveInstanceState() in the Bundle and restore it in onCreate(). If it's heavy data, you would be better off dumping it in a cache file.

If you have a data model, and want to use the same data across several activities, maybe a widget and possibly even a different app, you may want to consider building a ContentProvider to supply the data. It would live independently of the other parts of your application and manage access to the data. Other parts would query it for the data they would need.

The neat thing about that is, it abstracts the data away from the rest of the program. It can be accessed from anywhere and caching policies and everything is handled in a dedicated place. The drawback is, it's significantly more complicated.


Solution 3:

One possible solution would be to work with states. You basically have a boolean which indicates if your activity has performed a certain action.

If the action was performed you it won't reach that code again. Of course that flag must be saved somewhere in the Application context or in SharedPreferences.


Solution 4:

You can add this parameter to your intent to prevent reloading.

//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(new Intent(this,My.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));

Post a Comment for "How To Prevent Activity To Reload On Back Action"