开发者

How to save state during orientation change in Android if the state is made of my classes?

开发者 https://www.devze.com 2023-02-20 06:41 出处:网络
I was looking at the way Android handles orientation开发者_开发知识库 change for my application (I discovered that it restarts the mainactivity on orientation change. I\'ve seen that you can override

I was looking at the way Android handles orientation开发者_开发知识库 change for my application (I discovered that it restarts the mainactivity on orientation change. I've seen that you can override the method

protected void onSaveInstanceState(Bundle outState)

To save stuff, then have the in onStart. The problem is that I've my view with custom objects and a listview using a custom adapter. Everything is in a ArrayList of these objects, but I've noticed that you can't put arbitrary objects in the bundle! So how do I save the state?


Have you tried using: its work around ,

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

in Manifest file?

It does not work by default because , when you change the orientation onCreate will be called again and it redraws your view.

If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.

NOTE If you are using a different layout for landscape mode , by adding these parameters the layout for landscape mode will not be called.

Other way and Another way


EDIT: On newer versions of Android and with the compatibility library, retained fragments are usually the best way to handle keeping expensive-to-recreate data alive across activity destruction/creation. And as Dianne pointed out, retaining nonconfiguration data was for optimizing things like thumbnail generation that are nice to save for performance reasons but not critical to your activity functioning if they need to be redone - it's not a substitute for properly saving and restoring activity state.

But back when I first answered this in 2010:
If you want to retain your own (non view-state) data, you can actually pass an arbitrary object specifically for orientation changes using onRetainNonConfigurationInstance(). See this Android Developers blog post. Just be careful not to put any Views or other references to the pre-rotation Context/Activity in the object you pass, or you'll prevent those objects from being garbage collected and may eventually run out of memory (this is called a context leak).


First, you need to determine what is actually the "state" in your app. You haven't said what you are actually doing, but let me assume that the ArrayList of objects is the state the user is working with.

Second, decide what the lifecycle of this state actually is. Is it really tied to that activity? Or should the user not lose it if say their battery runs low, the device turns off, and they later return to your app? If the former, onSaveInstanceState() is correct; if the latter, you'll want to save to persistent storage in onPause().

For onSaveInstanceState() with custom objects, the key is to implement the Parcelable interface. This involves implementing the methods on Parcelable, as well as making a static CREATOR object in your class. Here's the code for a typical simple Parcelable class:

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/content/ComponentName.java

The key functions are the Parcelable implementation:

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/content/ComponentName.java#317

and the CREATOR static class:

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/content/ComponentName.java#355

(The static writeToParcel() and readFromParcel() are just conveniences that were done for that class and not required.)

Now that you have that, you can put your entire ArrayList of objects into the saved state Bundle with Bundle.putParcelableArrayList:

http://developer.android.com/reference/android/os/Bundle.html#putParcelableArrayList(java.lang.String, java.util.ArrayList)

In Activity.onCreate(), check to see if you have a savedState Bundle, and if so try to retrieve the ArrayList from that and use it if found, creating a new adapter and list view for the new activity that are used to display it.


but I've noticed that you can't put arbitrary objects in the bundle!

First make your custom objects Parcelable.
Then you can put them in to a bundle.

Everything is in a ArrayList of these objects

You can use putParcelableArrayList method in bundle to store an ArrayList of custom "parcelable" objects.


write your objects to JSON Strings using Google's Gson, then save them as a String. Then, build them back from the saved JSON Strings when rebuilding the Activity/Fragment

import com.google.gson.Gson;

public class MyClass {
    private int a;
    private String s;
    private OtherSerializableClass other;
    private List<String> list;

    public String toJson() {
        return new Gson().toJson(this);
    }

    public static ChatAPI_MessagesArray fromJson(String json){
       return new Gson().fromJson(json, YourClass.class);
    }

    // Getters
    ...

    // Setters
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消