我已经使用API结果构建了一个ArrayList。当用户转动手机时,我不希望它消失。
我应该如何处理onSaveInstanceState?
JSONObject json = new JSONObject(result);
JSONArray searchArray = json.getJSONArray("Search");
for (int i = 0; i < searchArray.length(); i++) {
JSONObject searchObject = searchArray.getJSONObject(i);
String title = searchObject.getString("Title");
String type = searchObject.getString("Type");
String year = searchObject.getString("Year");
String imdbID = searchObject.getString("imdbID");
movieList.add(new Movie(title, type, year, imdbID));
答案 0 :(得分:6)
假设您要跟踪的arrayList被称为myArrayList
活动中的此代码将满足您的目的:
对于字符串数组:
ArrayList myArrayList;
//put value of myArrayList in some other method
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("myArrayList", myArrayList);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myArrayList = savedInstanceState.getStringArrayList("myArrayList");
}
对于自定义对象数组:
制作物品&#39; class实现接口Parcelable
,然后将对象添加到ArrayList
。在您的情况下,制作Movie
类工具Parcelable
并将对象添加到movieList
。
然后使用相同的方法而不是putStringArrayList()
使用:
outState.putParcelableArrayList("movieList", movieList);
同样,使用:
movieList = (ArrayList<Movie>) savedInstanceState.getParcelableArrayList("movieList");
在onRestoreInstanceState()
方法中获取数组。