Trying to send a view's id with an intent. Getting "false"
This class has information that I want to send with an intent to another activity. When the image button "superman" is pressed the onClick() handler sends an intent to SuperheroActivity. But when I try and retrieve that information in the other activity I get "false".
public class MenuActivity extends Activity implements
OnClickListener {
private ImageButton superman;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
superman = (ImageButton) findViewById(R.id.superman);
superman.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(MenuActivity.this, SuperheroActivity.class);
intent.putExtra("id", v.getId());
startActivity(intent);开发者_如何转开发
}
}
This is the piece of code that tries to retrieve the information from the intent. Note: This is SuperheroActivity.
Intent intent = getIntent();
id = intent.getIntExtra("id", 0);
// This is just a dirty way for me to see the value of the id I am getting.
TextView text = (TextView) findViewById(R.id.superheroText);
text.setText(id);
The bug is in this line of code.
text.setText(id);
means the resource id (i.e String
resource id).
try replacing and using this.
text.setText(String.valueOf(id));
use id = intent..getExtras().getInt("id") to get data from the intent...
SuperheroActivity
Bundle extras = getIntent().getExtras();
id = extras.getInt("id");
TextView text = (TextView) findViewById(R.id.superheroText);
text.setText(id+"");
Get the bundle using getExtras()
Intent intent = getIntent();
id = intent.getExtras().getInt("id");
REMEMBER You cant setText(int)
! the int
must be a String
So change
TextView text = (TextView) findViewById(R.id.superheroText);
text.setText(id);
to
TextView text = (TextView) findViewById(R.id.superheroText);
text.setText(String.valueOf(id)); //change id to a string
精彩评论