Activity B 通過 putExtra("text", value) 傳遞數據,Activity A 使用 getStringExtra("Textview01") 取值結果為 null。
// Activity B (發送方)
Intent intent = new Intent(Next.this, Hw3Activity.class);
intent.putExtra("text", counted.getText().toString()); // Key: "text"
startActivity(intent);
// Activity A (接收方)
String s1 = getIntent().getStringExtra("Textview01"); // Key: "Textview01" 不匹配!
text.setText("You clicked the button " + s1 + " times.");
統一 Key 字符串,建議定義常量避免拼寫錯誤:
// 定義常量類
public class Extras {
public static final String EXTRA_CLICK_COUNT = "extra_click_count";
}
// 發送
intent.putExtra(Extras.EXTRA_CLICK_COUNT, counted.getText().toString());
// 接收
String count = getIntent().getStringExtra(Extras.EXTRA_CLICK_COUNT);
若需返回結果,應使用 startActivityForResult + onActivityResult:
// Activity A
startActivityForResult(new Intent(this, Next.class), REQUEST_CODE);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String count = data.getStringExtra(Extras.EXTRA_CLICK_COUNT);
// 更新 UI
}
}
// Activity B (返回時)
Intent result = new Intent();
result.putExtra(Extras.EXTRA_CLICK_COUNT, count);
setResult(RESULT_OK, result);
finish();
Intent 傳值 Key 必須完全一致(區分大小寫),使用常量定義是防止此類低級錯誤的最佳實踐。