Home » Android » android – Why Bundle object is always null on onCreate()?

android – Why Bundle object is always null on onCreate()?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am trying get into Android programming, and for I am taken some examples from a book.
In on of these example is requested to put the following code:

public class ExemploCicloVida extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Log.i(TAG, getClassName() + " onCreate() called on: " + icicle);

        TextView t = new TextView(this);
        t.setText("Exemplo de ciclo de vida de uma Activity.\nConsulte os logs no LogCat");
        setContentView(t);
    }
}

I wonder why Bundle object is always null on this case.

How to&Answers:

The bundle will be null if there is no previously-saved state.

This is mentioned in the Activity API documentation.

Answer:

In my case, the reason was that the specific activity did not have a theme declared in the manifest file.

To fix this, open AndroidManifest.xml, click Application, select the crashing activity in Application Nodes and add the theme in the Theme field of Attributes. In my case, it was

@style/Theme.AppCompat.Light.DarkActionBar

but you could copy the theme from one of your other activities.

P.S.: I know this is an answer to an old question, but I’ve stumbled upon it while searching for a fix and didn’t find a working solution so this might help others.

Answer:

Run this code and rotate the screen by pressing Ctrl+F11. The bundle will not be null.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (savedInstanceState != null) {
        Toast.makeText(this, savedInstanceState.getString("s"),
                Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putString("s", "hello");
}

onSaveInstanceState(Bundle) will be called. Then, the activity object is created and onCreated(Bundle) will be called with non-null Bundle savedInstanceState.

Answer:

I guess you would like to read the parameters getting in to your activity. Use this function:

protected String getStringExtra(Bundle savedInstanceState, String id) {
String l;
l = (savedInstanceState == null) ? null : (String) savedInstanceState
            .getSerializable(id);
if (l == null) {
    Bundle extras = getIntent().getExtras();
    l = extras != null ? extras.getString(id) : null;
}
return l;
}