In Activity.onCreate(), why does Intent.getExtras() sometimes return null?

筅森魡賤 提交于 2019-12-04 22:32:49

You can get it like this:

getIntent().getStringExtra(key);

Or:

getIntent().getExtras().getString(key)

And set it like this in "FromActivity":

Bundle extras = new Bundle();
extras.putString(key, value);
intent.putExtras(extras);
//And start your activity...

Or:

intent.putExtra(key, string);
//And start your activity...

Either way should work, Hope this helps...

Regards!

This was probably a false alarm; it's more likely due to our own instance variable being null:

class ToActivity extends Activity {

    public static final String SERVER_PARAM = "server";
    public static final String UUID_PARAM = "uuid";
    public static final String TEMPLATE_PARAM = "template";

    private State state;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        state = initializeState();
        // MISSING NULL CHECK HERE!

        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            finish();
            return;
        }

        // do stuff with state and extras
    }
}

theoretically, the Intent that starts your activity could come from anywhere, e.g. another program

You got a null pointer error, did you miss some initialization? And can you tell us which line of your code has this error. BTW, if you have many activities to handle, set a flag for your intent is a good idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!