我创建了一个Activity,并使用FragmentStatePagerAdapter和2个片段。
在onSaveInstanceState上,我正在保存两个片段。
@Override
protected void onSaveInstanceState(Bundle outState) {
try {
getSupportFragmentManager().putFragment(outState,
BirthDetailInputFragment.class.getName(),
birthDetailInputFragment);
getSupportFragmentManager().putFragment(outState,
SearchBirthDetailsFragment.class.getName(),
searchBirthDetailsFragment);
} catch (Exception e) {
e.printStackTrace();
}
super.onSaveInstanceState(outState);
}
这样我就可以在onCreate()中获取保存的实例,如下所示。
if (savedInstanceState != null) {
try {
birthDetailInputFragment = (BirthDetailInputFragment) getSupportFragmentManager()
.getFragment(savedInstanceState,
BirthDetailInputFragment.class.getName());
searchBirthDetailsFragment = (SearchBirthDetailsFragment) getSupportFragmentManager()
.getFragment(savedInstanceState,
SearchBirthDetailsFragment.class.getName());
} catch (Exception e) {
e.printStackTrace();
}
} else {
searchBirthDetailsFragment = new SearchBirthDetailsFragment();
birthDetailInputFragment = new BirthDetailInputFragment();
}
但是当我改变方向时,它给了我以下例外 java.lang.NullPointerException:尝试在上述catch块中的空对象引用上调用虚拟方法'int java.util.ArrayList.size()' 。
>任何指导将不胜感激。
答案 0 :(得分:0)
将数据保存在onSaveInstanceState中。 并在onRestoreInstanceState中还原数据-而不是oncreate();