android return activity extras returns null
When trying to pass data from one activity to another it works fine in one direction parent>>child. But the return path child>>parent crashes I think with a null pointer exception. Now I can trap the null easy enough but cant figure out where my passed int is getting lost?
How do you debug this type of problem – any insight etc…
the crash occurs of the line: int binVal = extras.getInt("binVal");
// when leaving the child开发者_开发百科 activity
OnClickListener mReturnListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
intent.putExtra("binVal", (int)binVal);
setResult(Activity.RESULT_OK, intent);
finish();
}
};
//on return to the parent actvity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SET_BIN_TEMP:
if (resultCode == RESULT_OK) {
Bundle extras = getIntent().getExtras();
if (extras == null)
Toast.makeText(PilotActivity.this, "null returned!", Toast.LENGTH_SHORT).show();
else {
int binVal = extras.getInt("binVal");
text.setText(Integer.toString(binVal));
}
}
return;
}
}
Look at your onActivityResult(...)
parameters...
protected void onActivityResult(int requestCode, int resultCode, Intent data)
When an Activity that has been started with startActivityForResult
returns, the Intent
returned is the parameter data
.
In your 'parent' Activity you are using its getIntent()
method which returns the Intent
(if any) which started the Activity originally.
Instead of...
Bundle extras = getIntent().getExtras();
...you should use...
Bundle extras = data.getExtras();
I had problems with this in the past and had to do something like the code sample below:
OnClickListener mReturnListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = getIntent();
intent.putExtra("binVal", (int)binVal);
if (getParent() == null)
YourActivity.this.setResult(Activity.RESULT_OK, intent);
else
YourActivity.this.getParent().setResult(Activity.RESULT_OK, intent);
finish();
}
};
精彩评论