null value in getIntent.getExtras.getString()

2019-02-26 05:06发布

问题:

This is my code in my first activity:

Intent i = new Intent(this, OtherScreen.class);
    i.putExtra("id1", "first");
    i.putExtra("id2", "second");
    startActivity(i);

where first,second are the values I want to be passed. and on my other class i have this:

Intent i = getIntent();
        Bundle extras = i.getExtras();
        String result = extras.getString("id1");
        System.out.println("yeah"+result);

but after i run it, my result is null.Can you help me? If I write my getString in that ways, I am getting syntax errors.

String result = extras.getString(id1); //id1 cannot be resolved to a variable
String result = extras.getString("id1","default value"); // remove argument

回答1:

Intent i = new Intent(yourcurrentactivity.this, OtherScreen.class);

i.putExtra("id1", "first");
i.putExtra("id2", "second");
startActivity(i);

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String result = extras.getString("id1");                
    System.out.println("yeah"+result);
}


回答2:

Alternatively for more accuracy, you can use if(getIntent.hasExtras("id11")' before actually getting extras from the bundle and do some action if its null



回答3:

try:

getIntent().getStringExtra("id11");

Of course its best to FIRST check if it even has the extra before you even go for it.

Ref:

http://developer.android.com/reference/android/content/Intent.html#getStringExtra(java.lang.String)



回答4:

You may try :String result = extras.get("id1");



回答5:

I was also having trouble with null values. @YuDroid's suggestion to use if (getIntent.hasExtras("id11") is a good idea. Another safety check that I found when reading the Bundle documentation, though, is

getString(String key, String defaultValue)

That way if the string does not exist you can provide it with a default value rather than it being returned null.

So here is @AprilSmith's answer modified with the default String value.

Intent i = new Intent(yourcurrentactivity.this, OtherScreen.class);

i.putExtra("id1", "first");
i.putExtra("id2", "second");
startActivity(i);

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String result = extras.getString("id1", "myDefaultString"); // This line modified
    System.out.println("yeah"+result);
}


回答6:

If anybody still having this issue..here is the solution

the datatype you are passing in first activity should be same in receiving end.

'Intent myIntent = new Intent(D1Activity.this, D2Activity.class);'
        'myIntent.putExtra("dval", dval);'
       ' D1Activity.this.startActivity(myIntent);'

in D2Activity

Bundle extras = getIntent().getExtras();
    if (extras != null) {;
        edval = extras.getInt ( "dval" );
    }

here extras.getString() will not work as we passed an Int not a string