简体   繁体   中英

nullpointerexception when use getIntent().getExtras().getString

I want to pass a value in a activity to another activity and use this code

            Intent i = new Intent(MainActivity.this,ListActivity.class);
            i.putExtra("position","ایران");
            startActivity(i);

and in other activity for return variable use this code

        value = getIntent().getExtras().getString("position");

Now when I run the program it gives this error:

java.lang.nullpointerexception

Please help me.

This is the right way to retrieve string extra:

value = getIntent().getStringExtra("position");

Explanation

Why getExtras() does not work: getExtras() returns a bundle which was previously put inside intent using putExtras(bundle). so, the code would look like:

    // Put position inside intent using extras:
    Intent intent = new Intent();
    Bundle extras = new Bundle();
    extras.putString("position",position);
    intent.putExtras(extras);

    // Retrieve position:
    getIntent().getExtras().getString("position");

But that's a lot more code, storing extra inside the intent directly is much more cleaner way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM