![](/img/trans.png)
[英]''intent.getExtras().getString'' app crashes when reopen
[英]Intent.getExtras not working
在一個類中,我在onCreate方法外部聲明了以下變量:
Double isowei2 = 9.36;
Double iso2 = 10.54;
在onCreate方法中,我有這個:
final Intent start = new Intent(IsoAbun.this, IsoAbunCal.class);
public void onClick(View arg0) {
isowei2 = 9.0;
iso2 = isowei2;
start.putExtra("iso2", iso2);
startActivity(start);
}
那兩個代碼在一個類中。 在另一個類中,我在onCreate方法中具有以下內容:
Bundle b = getIntent().getExtras();
Double iiso2 = 0.0;
iiso2 = b.getDouble("iso2");
從我從這個理解,它應該做的是,當我點擊來自第一類的按鈕,它reassignes isowei2
至9.0,設置iso2
到9.0,然后創建一個名為ISO2鍵,傳遞的價值iso2
,這是9.0,然后啟動意圖/活動。 當啟動活動時,它應該做的是創建一個包和一個double變量,然后將iiso2
設置為9.0的iso2
。 我沒有顯示顯示iiso2
值的iiso2
,但是問題是它不顯示9.0,而是顯示10.54。 有什么幫助嗎?
您需要在onCreate中進行如下設置:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<your layout>);
final Intent start = new Intent(this, <OtherClass>.class);
Button btn = (Button)findViewById(R.id.btnId);//find from your activity xml, your button Id
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
isowei2 = 9.0;
iso2 = isowei2;
start.putExtra("iso2", iso2);
startActivity(start);
}
});
}
在另一個類oncreate方法中,可以使用TextView進行查看,例如:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
Double iiso2 = 0.0;
iiso2 = b.getDouble("iso2");
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(20);
textView.setText(iiso2.toString());
setContentView(textView);
}
如果您沒有為按鈕分配ID,請參見以下示例,以了解其在布局xml中的外觀:
<Button
android:id="@+id/btnId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
與其將數據作為額外的意圖傳遞,不如創建具有數據的捆綁包並將該捆綁包通過意圖傳遞。
所以像這樣:
Bundle bundle = new Bundle();
bundle.putDouble("key", myDouble);
startActivity(new Intent(this, NextActivity.class).putExtras(bundle));
然后在接收活動中:
Bundle bundle = getIntent().getExtras();
if (bundle != null)
double myDouble = bundle.getDouble("key");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.