如何在Android屏幕旋转上保存自定义ArrayList?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12503836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:50:14  来源:igfitidea点击:

How to save custom ArrayList on Android screen rotate?

androidobjectarraylistparcelablescreen-rotation

提问by Kalina

I have an ArrayListwith custom objects that I would like to be able to save and restore on a screen rotate.

我有一个ArrayList自定义对象,我希望能够在屏幕旋转时保存和恢复。

I know that this can be done with onSaveInstanceStateand onRestoreInstanceStateif I were to make the ArrayListits own class, which implements either Parcelableor Serializable... But is there a way to do this without creating another class?

我知道,这是可以做到的onSaveInstanceStateonRestoreInstanceState如果我让ArrayList自己的类,它实现了无论是Parcelable还是Serializable......但是,有没有办法做到这一点,而无需创建另一个类?

回答by Sam

You do not need to create a new class to pass an ArrayList of your custom objects. You should simply implement the Parcelable class for your object and use Bundle#putParcelableArrayList()in onSaveInstanceState()and onRestoreInstanceState(). This method will store an ArrayList of Parcelables by itself.

您不需要创建新类来传递自定义对象的 ArrayList。您应该简单地实现Parcelable类的对象,并使用束#putParcelableArrayList()onSaveInstanceState()onRestoreInstanceState()。此方法将单独存储 Parcelables 的 ArrayList。



Because the subject of Parcelables (and Serializables and Bundles) sometimes makes my head hurt, here is a basic example of an ArrayList containing custom Parcelable objects stored in a Bundle. (This is cut & paste runnable, no layout necessary.)

因为 Parcelables(以及 Serializables 和 Bundles)的主题有时让我头疼,这里是一个包含存储在 Bundle 中的自定义 Parcelable 对象的 ArrayList 的基本示例。(这是可以剪切和粘贴运行的,不需要布局。)

Implementing Parcelable

实现 Parcelable

public class MyObject implements Parcelable {
    String color;
    String number;

    public MyObject(String number, String color) {
        this.color = color;
        this.number = number;
    }

    private MyObject(Parcel in) {
        color = in.readString();
        number = in.readString();
    }

    public int describeContents() {
        return 0;
    }

    @Override
    public String toString() {
        return number + ": " + color;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeString(color);
        out.writeString(number);
    }

    public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
        public MyObject createFromParcel(Parcel in) {
            return new MyObject(in);
        }

        public MyObject[] newArray(int size) {
            return new MyObject[size];
        }
    };
}

Save / Restore States

保存/恢复状态

public class Example extends ListActivity {
    ArrayList<MyObject> list;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState == null || !savedInstanceState.containsKey("key")) {
            String[] colors = {"black", "red", "orange", "cyan", "green", "yellow", "blue", "purple", "magenta", "white"};
            String[] numbers = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

            list = new ArrayList<MyObject>();
            for(int i = 0; i < numbers.length; i++) 
                list.add(new MyObject(numbers[i], colors[i]));
        }
        else {
            list = savedInstanceState.getParcelableArrayList("key");
        }

        setListAdapter(new ArrayAdapter<MyObject>(this, android.R.layout.simple_list_item_1, list));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList("key", list);
        super.onSaveInstanceState(outState);
    }
}

回答by Techwolf

You can use onRetainNonConfigurationInstance(). It allows you to save any object before an configuration change, and restore it after with getLastNonConfigurationInstanceState().

您可以使用onRetainNonConfigurationInstance(). 它允许您在配置更改之前保存任何对象,并在使用getLastNonConfigurationInstanceState()之后恢复它。

Inside the activity:

活动内部:

    @Override
    public Object onRetainNonConfigurationInstance() {
        return myArrayList;
    }

Inside onCreate():

内部onCreate()

    try{
        ArrayList myArrayList = (ArrayList)getLastNonConfigurationInstance();
    } catch(NullPointerException e) {}

Handling Runtime Changes: http://developer.android.com/guide/topics/resources/runtime-changes.htmlDocumentation: http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance%28%29

处理运行时更改:http: //developer.android.com/guide/topics/resources/runtime-changes.html文档:http: //developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance%28 %29

回答by Hamdy Abd El Fattah

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    ArrayList<Integer> id=new ArrayList<>();
    ArrayList<String> title=new ArrayList<>();
    for(int i=0;i<arr.size();i++){
        id.add(arr.get(i).id);
        title.add(arr.get(i).title);
    }
    outState.putIntegerArrayList("id",id);
    outState.putStringArrayList("title",title);
}

回答by Andriya

Yes, you can save your composite object in shared preferences. Let's say:

是的,您可以在共享首选项中保存复合对象。让我们说:

Student mStudentObject = new Student();
     SharedPreferences appSharedPrefs = PreferenceManager
      .getDefaultSharedPreferences(this.getApplicationContext());
      Editor prefsEditor = appSharedPrefs.edit();
      Gson gson = new Gson();
      String json = gson.toJson(mStudentObject);
      prefsEditor.putString("MyObject", json);
      prefsEditor.commit(); 

and now you can retrieve your object as:

现在您可以将对象检索为:

     SharedPreferences appSharedPrefs = PreferenceManager
     .getDefaultSharedPreferences(this.getApplicationContext());
     Editor prefsEditor = appSharedPrefs.edit();
     Gson gson = new Gson();
     String json = appSharedPrefs.getString("MyObject", "");
     Student mStudentObject = gson.fromJson(json, Student.class);