How to I launch an activity with an Intent and pass a variable in the new activity?
So right now I'm using the zxing barcode scanner in my app. Here is example code(generic):
if(position == 0){
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
开发者_C百科 intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
contents = intent.getStringExtra("SCAN_RESULT");
format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
Intent i = new Intent(Main.this, BarcodeScanner.class);
startActivity(i);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
So when launching the BarcodeScanner.class
, I also want to pass contents
into it. How would I go about doing that?
Use Bundle inside intents to pass data from one activity to the other. In your case, you would have to do something like -
Intent intent = new Intent(Main.this,BarcodeScanner.class);
//load the intent with a key "content" and assign it's value to content
intent.putExtra("content",contents);
//launch the BarcodeScanner activity and send the intent along with it
//note that content is passed in as well
startActivity(intent);
The information is stored in a 'Bundle' object that lives inside the Intent - the Bundle is created when you call the putExtras() method of the Intent object
The same way you passed "SCAN_MODE"
to the other activity, by calling putExtra("some key", contents)
before calling startActivity()
, and then inside BarcodeScanner call this.getIntent().getStringExtra("some key")
精彩评论