0

My program runs an activity on startup, afterwards it sends an Intent opening another activity. The first time this happens, I want to save the information from the Intent to the savedInstanceState so whenever the app is opened again that information is available. The code looks like this:

savedInstanceState.putString("name", getIntent().getStringExtra("name"));
savedInstanceState.putString("font", getIntent().getStringExtra("font"));
savedInstanceState.putInt("background", getIntent().getIntExtra("background", R.drawable.bg1big));

However I continue to get a NullPointerException saying

Attempt to invoke virtual method 'void android.os.Bundle.putString(java.lang.String, java.lang.String)' on a null object reference.

koceeng
  • 2,169
  • 3
  • 16
  • 37

2 Answers2

0

You basically need to overwrite onSaveInstanceState() and onRestoreInstanceState() to store and retrieve the values that you want. Have a look at this answer - https://stackoverflow.com/a/151940/1649353

Community
  • 1
  • 1
Ambuj Kathotiya
  • 369
  • 4
  • 18
0

savedInstanceState is what you were given if something was saved last time - it's what was reloaded. even if it isn't null, you shouldn't add anything to it, it won't persist. Do this instead:

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    bundle.putString("name", mName);        
    bundle.putString("font", mFont);      
    bundle.putInt("background", mBackground);
}

And then in onCreate and onRestoreInstanceState you can read the values and populate those variables you'll later save

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    mName = savedInstanceState.getString("name");     
    mBackground = savedInstanceState.getString("background");        
    mFont = savedInstanceState.getString("font");      
}
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124