Skip to content Skip to sidebar Skip to footer

Onbackpressed - Avoid Destroying Activity

I have two activities - activity A starts activity B. Then activity B loads some stuff from database, and visualizes the data. It takes some time (5-10sec) to fully initialize all

Solution 1:

You can use Fragments, but what you really want to do is cache the information. Otherwise you'll reload on device rotation anyways (unless you use Fragments and setRetainInstance to true, but this can cause other headaches).

I would use a CursorLoader on Activity B's onCreate. onLoadFinished you cache the result and setup your UI. On subsequent loads the results are cached and you forego the loader. What's more, using the CursorLoader will alert you if the underlying database results change.

Solution 2:

I think you do not see the problem from the right point of view.

I'd say that you can't prevent B to be destroyed if Android wants to (because it's up to it to handle the activities). However, you have the choice to move all the long initialisation in a third class which can be persisted all the time. So you should make this init phase independant from your B activity.

I think that putting all this in an attribute of your Application class would be a good idea.

Solution 3:

Solution 4:

Use SharedPreferences to store key-value pairs then use getSharedPreferences() to retrieve them.

Solution 5:

When you press back button Activity b is destroyed. It is how android works. I would not try to override the default functionality

Once you get data from data base you can cache then some where and load it.

http://developer.android.com/guide/topics/data/data-storage.html. Check the topic under Saving cache files.

Post a Comment for "Onbackpressed - Avoid Destroying Activity"