Saving some data on orientation change in Android

这一生的挚爱 提交于 2019-11-30 20:58:47

Using static variables/classes is a bad approach in terms of maintainability and debugging.


I have been using Activity.onRetainNonConfigurationInstance but I found out just now that this is deprecated (probably since honeycomb or later). Activity.onRetainNonConfigurationInstance

Using this method, just call Activity.getLastNonConfigurationInstance to retrieve the same object you returned in the onRetainNonConfigurationInstance. Be sure to check for null and cast to the right class (you can return/get any class). Activity.getLastNonConfigurationInstance

A sample usage in pseudo-code would be:

onRetainNonConfigurationInstance:
    return "I need to remember this next time";

onCreate:
    ...
    String messageToShow = null;
    Object data = getLastNonConfigurationInstance();
    if(data != null)
        messageToShow = (String)data;
    else
        messageToShow = "Nothing to show";

So, if you are targetting up to 2.x.x you can use that method. Otherwise, google recommends you to use Fragment.setRetainInstance. This is backwards compatible via the compability package.

Fragment.setRetainInstance

Save the items in a parent activity or static utility class.

Otherwise, you can use the manifest to tell the app to not destroy the activity on screen resizes. Check out this article: http://developer.android.com/guide/topics/resources/runtime-changes.html

Actually there is a very nice article on the Android Developer site which covers this topic.

Some devices, like the T-Mobile G1, can change their hardware configuration at runtime. For instance, when you open the keyboard, the screen change from the portrait orientation to the landscape orientation.

To make Android app development easier, the Android system automatically handles configuration change events and restarts the current activity with the new configuration.

[...]

While this behavior is really powerful, since your application adapts automatically to the device's configuration at runtime, it is sometimes confusing for new Android developers, who wonder why their activity is destroyed and recreated.

Facing this "issue," some developers choose to handle configuration changes themselves which is, in general, a short-term solution that will only complicate their lives later.

[...]

The full article.

Process running your activity will not be restarted. Android framework will just create a new instance of your activity. So as simplest solution you can store your data in static variables.

you can try using sharedpreferences:

editor edit = preferences.edit(); edit.putString("username", "new_value_for_user"); edit.commit();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!