51

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

我知道这可以做到,onSaveInstanceState如果onRestoreInstanceState我要创建ArrayList它自己的类,它实现Parcelable或者Serializable......但是有没有办法在不创建另一个类的情况下做到这一点?

4

4 回答 4

90

您无需创建新类来传递自定义对象的 ArrayList。您应该简单地为您的对象实现 Parcelable 类并在 和 中使用Bundle # putParcelableArrayList()。此方法将自行存储 Parcelables 的 ArrayList。onSaveInstanceState()onRestoreInstanceState()


因为 Parcelables(以及 Serializables 和 Bundles)的主题有时让我头疼,这里有一个 ArrayList 的基本示例,其中包含存储在 Bundle 中的自定义 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];
        }
    };
}

保存/恢复状态

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);
    }
}
于 2012-09-19T22:40:07.593 回答
3

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

活动内部:

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

内部onCreate()

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

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

于 2012-09-20T00:11:54.827 回答
2
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);
}
于 2019-02-19T00:54:36.353 回答
-3

是的,您可以将复合对象保存在共享首选项中。比方说:

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(); 

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

     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);
于 2015-07-06T11:37:44.697 回答