保存自定义对象在屏幕上旋转在片段或活动
我知道这个问题是非常普遍的,我已经阅读了很多不同的答案,但没有一个适合我的问题。在我的应用程序中,我有一个活动,并在rhye活动中加载一个片段。我还将一些数据(以Bundle的形式)发送到片段。所以我的问题是当屏幕旋转时,我保存片段在onSaveInstanceState
活动方法和签入onCreate方法天气savedInstance为null或不,并在此基础上加载片段。 活动代码:保存自定义对象在屏幕上旋转在片段或活动
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putParcelable(Const.TAG_REQ_CUSTOM,DetailsItems);
outState.putString(Const.TAG_FLOW, Const.TAG_MAIN_FLOW);
getSupportFragmentManager().putFragment(outState,"current_fragment",fragment);
}
onCreate方法:
if (findViewById(R.id.fragment_frame) != null) {
if (savedInstanceState != null) {
// this invoke when screen rotate but the app crash
DetailsItems = savedInstanceState.getParcelable(Const.TAG_REQ_CUSTOM);
String flow = savedInstanceState.getString(Const.TAG_FLOW);
ft = getSupportFragmentManager().getFragment(savedInstanceState,"current_fragment");
mFragmentManager=getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
bundle= new Bundle();
bundle.putString(Const.TAG_FLOW, flow);
bundle.putParcelable(Const.TAG_REQ_BOOKING_DETAILS, bookingDetailsItems);
ft.setArguments(bundle);
mFragmentTransaction.replace(R.id.fragment_frame, ft).commit();
}else{
// load fragment on first time
}
}
所以我的问题是:我在哪里有保存自定义对象(父活动或片段)? 当我保存的实例并不比应用crashesh和日志null是:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
使用此代码在活动时间:
if (findViewById(R.id.fragment_frame) != null) {
if (savedInstanceState != null) {
fragment =getSupportFragmentManager().getFragment(savedInstanceState,"current_fragment");
}else{
// load fragment on first time
}
}
和片段:
//save custom object
@Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelable("key",customObject);
}
//now retrieve here
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
customObject= savedInstanceState.getParcelable("key");
}
看看onRetainNonConfigurationInstance()
和getLastNonConfigurationInstance()
从文档:
被系统调用,为的一部分摧毁由于配置更改而导致的活动,,当知道将立即为新配置创建新实例时。您可以返回您在此处喜欢的任何对象,包括活动实例本身,稍后可以通过在新活动实例中调用getLastNonConfigurationInstance()来检索它。
所以在这里我救了我的自定义对象....在活动或碎片 – techDigi
你可以从文档的链接看到,这些方法在'Activity'定义。 – azizbekian
您应该使用ViewModel
。 ViewModel
是专门为此目的而制作的。
从文档:
视图模型是一类负责为一个活动或一个片段制备和管理数据。它还处理Activity/Fragment与其他应用程序的通信(例如调用业务逻辑类)。
假定对象实现'Parcelable'接口,而OP则询问如何保存/恢复任意对象。 – azizbekian