Reputation: 331
I have a problem with saving state and restoring it. I have two variables that I want to save when another activity is started and restore them when I press home back button. There is no problem when I'm pressing soft back button. I'm getting null pointer exception on bundle.getString() method.
Thanks in advance.
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);
}
Upvotes: 0
Views: 114
Reputation: 331
Thanks everyone for your support.
Actually I solved problem by storing needed data in static variables and getting them when bundle is null.
Thanks again.
Upvotes: 0
Reputation: 9223
@Override
protected void onSaveInstanceState(Bundle outState)
{
outState.putString("CATEGORY_ID", state_category_id);
outState.putString("CATEGORY_NAME", state_category_name);
super.onSaveInstanceState(outState);
}
And Retrieve data after getting back from different activity :
@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);
}
Upvotes: 2
Reputation: 35549
put this condition in else part
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
Upvotes: 1