Intent Bundle returns Null every time? [duplicate]

2019-01-29 00:21发布

This question already has an answer here:

I have some extras sent to a new intent. There it grabs the bundle and tests if it is null. Every single time it is null even though I am able to get the values passed and use them.

Can anyone see what is wrong with the if statement?

Intent i = getIntent();
Bundle b = i.getExtras();
int picked = b.getInt("PICK");
int correct = b.getInt("CORR");
type = b.getString("RAND");
if(b == null || !b.containsKey("WELL")) {
    Log.v("BUNDLE", "bun is null");
} else {
    Log.v("BUNDLE", "Got bun well");
}

EDIT: Heres where the bundle is created.

Intent intent = new Intent(this, app.pack.son.class);
Bundle b = new Bundle();
b.putInt("PICK", pick);
b.putInt("CORR", corr);
b.putString("RAND", "yes");
intent.putExtras(b);
startActivity(intent);

3条回答
冷血范
2楼-- · 2019-01-29 01:01

Well, you test b == null after using it, which must be wrong. Also are you missing the initial if?

After edits
You don't put "WELL" inside the bundle, so the string "bun is null" is logged. The b must be non-null or you would have a crash at your hands. Try changing your if sentences to this and report what you get:

if (b == null) {
    Log.v("BUNDLE", "bun is null");
} else if (!b.containsKey("WELL")) {
    Log.v("BUNDLE", "bun doesn't contain WELL");
else {
    Log.v("BUNDLE", "Got bun well");
}
查看更多
何必那么认真
3楼-- · 2019-01-29 01:01

I change your if statement to match the log message. Please run the program and check the log message.

if(b == null) {
    Log.v("BUNDLE", "bun is null");
} else {
    if (b.containsKey("WELL")) {
        Log.v("BUNDLE", "Got bun well");
    }
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-29 01:02

I don't think the problem is that your bundle is null. It can't be because you'd get a NullPointerException much sooner.

The problem is that your error message is wrong. Change this:

if(b == null || !b.containsKey("WELL")) {
    Log.v("BUNDLE", "bun is null");
} else {
    // ...
}

To this:

if (!b.containsKey("WELL")) {
    Log.v("BUNDLE", "bundle does not contain key WELL");
} else {
    // ...
}

And the reason why the bundle doesn't contain this key, is because you didn't add it.

查看更多
登录 后发表回答