如何保存在Android上旋转屏幕定制的ArrayList?(How to save custom

2019-06-18 05:42发布

我有一个ArrayList与我想能够保存并在屏幕旋转恢复自定义对象。

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

Answer 1:

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


由于Parcelables并(与Serializables和包)的主题有时会让我头疼,这里是包含存储在一个Bundle定制Parcelable对象的ArrayList的一个基本的例子。 (这是复制粘贴必要的运行的,没有布局。)

实现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);
    }
}


Answer 2:

您可以使用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



Answer 3:

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


Answer 4:

是的,你可以保存你的组合对象共享偏好。 比方说:

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


文章来源: How to save custom ArrayList on Android screen rotate?