我在保存状态和恢复时遇到问题。我有两个变量,我想在另一个活动启动时保存,并在我按回原点后退按钮时恢复它们。当我按下软后退按钮时没有问题。我在bundle.getString()方法上得到空指针异常。
提前致谢。
if (savedInstanceState != null)
{
cat_id = savedInstanceState.getString("CATEGORY_ID");
cat_name = savedInstanceState.getString("CATEGORY_NAME");
}
else
{
Bundle extras = getIntent().getExtras();
cat_id = extras.getString("CATEGORY_ID"); //here I'm getting an exception
cat_name = extras.getString("CATEGORY_NAME");
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
outState.putString("CATEGORY_ID", state_category_id);
outState.putString("CATEGORY_NAME", state_category_name);
super.onSaveInstanceState(outState);
}
答案 0 :(得分:2)
@Override
protected void onSaveInstanceState(Bundle outState)
{
outState.putString("CATEGORY_ID", state_category_id);
outState.putString("CATEGORY_NAME", state_category_name);
super.onSaveInstanceState(outState);
}
从不同活动回来后检索数据:
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("CATEGORY_ID")) {
cat_id = extras.getString("CATEGORY_ID");
}
if (savedInstanceState.containsKey("CATEGORY_NAME")) {
cat_name = extras.getString("CATEGORY_NAME");
}
}
super.onRestoreInstanceState(savedInstanceState);
}
答案 1 :(得分:1)
将这个条件放在其他部分
if(getIntent().hasExtra("CATEGORY_ID"))
cat_id = extras.getString("CATEGORY_ID");
else
cat_id=//assign default id
if(getIntent().hasExtra("CATEGORY_NAME"))
cat_name = extras.getString("CATEGORY_NAME");
else
cat_name=//assign default name
答案 2 :(得分:0)
感谢大家的支持。
实际上,我通过将所需数据存储在静态变量中并在bundle为null时获取它们来解决问题。
再次感谢。