我不知道如何在onSavedInstance中保存bean类的对象,并通过将savedInstanceState检查为null来将其检索回onCreate。
到目前为止,我一直在尝试使用此代码,但无法保存/检索值: -
public class BookActivity extends Activity{
private ArrayList<Bitmap> bitmaps = null;
private ArrayList<Book> bookData = null; //Book is the bean class
private TextView bookTitle = null;
private ArrayList<Feature> bookIds = null; // Another bean class
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putSerializable("bookThumb", bookData);
savedInstanceState.putSerializable("bookBitmaps", bitmaps);
savedInstanceState.putSerializable("featureBook", bookIds);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.penguin_main);
if(savedInstanceState!=null){
bookData = (ArrayList<String>) savedInstanceState.getSerializable("bookThumb");
bookData = (ArrayList<String>) savedInstanceState.getSerializable("bookThumb");
bookData = (ArrayList<String>) savedInstanceState.getSerializable("bookThumb");
}
else{
Toast msg = Toast.makeText(getApplicationContext(), "Values Not Restored!!!", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
}
}
}
如何保存我的位图和Book的对象,以便它不会在方向更改时创建类的新实例?
答案 0 :(得分:2)
您可以将它们保存为Parcelable ArrayLists
savedInstanceState.putParcelableArrayList("bookThumb", bookData);
savedInstanceState.putParcelableArrayList("bookBitmaps", bitmaps);
savedInstanceState.putParcelableArrayList("featureBook", bookIds);
但是,Book
和Feature
类需要实现Parcelable
才能实现此目的。位图已经是一个可分类的类