通過 Activity 中的 Intent 傳遞不同的資料

1.傳遞整數資料:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0); // set 0 as the default value if no value for intVariableName found

2.傳遞雙重資料:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("doubleVariableName", doubleValue);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
double doubleValue = mIntent.getDoubleExtra("doubleVariableName", 0.00); // set 0.00 as the default value if no value for doubleVariableName found

3.傳遞字串資料:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("stringVariableName", stringValue);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
String stringValue = mIntent.getExtras().getString("stringVariableName");

要麼

Intent mIntent = getIntent();
String stringValue = mIntent.getStringExtra("stringVariableName");

4.傳遞 ArrayList 資料:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putStringArrayListExtra("arrayListVariableName", arrayList);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
arrayList = mIntent.getStringArrayListExtra("arrayListVariableName");

5.傳遞物件資料:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("ObjectVariableName", yourObject);
startActivity(myIntent);

ReceiverActivity

Intent mIntent = getIntent();
yourObj = mIntent.getSerializableExtra("ObjectVariableName");

注意: 請記住,你的自定義類必須實現 Serializable 介面。

6.傳遞 HashMap <String,String>資料:

SenderActivity

HashMap <String,String> hashMap;

Intent mIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
mIntent.putExtra("hashMap", hashMap);
startActivity(mIntent);

ReceiverActivity

Intent mIntent = getIntent();    
HashMap<String, String> hashMap = (HashMap<String, String>)
mIntent.getSerializableExtra("hashMap");

7.傳遞點陣圖資料:

SenderActivity

Intent myIntent = new Intent(SenderActivity.this, ReceiverActivity.class);
myIntent.putExtra("image",bitmap);
startActivity(mIntent);

ReceiverActivity

Intent mIntent = getIntent();
Bitmap bitmap = mIntent.getParcelableExtra("image");