2016-12-24 23 views
0

我一直試圖使用Intent在兩個活動之間傳遞多個值(不同類型)。到目前爲止,我已經試過這兩種方法:Android:無法將多個值放入Intent/Bundle

Intent intent = new Intent(context, Receiver.class); 
Bundle bundle = new Bundle(); 
bundle.putInt("key1", v1); 
bundle.putString("key2", v2); 
bundle.putString("key3", v3); 
bundle.putInt("key4", v4); 
intent.putExtras(bundle); 

和:

Intent intent = new Intent(context, Receiver.class); 
intent.putInt("key1", v1); 
intent.putString("key2", v2); 
intent.putString("key3", v3); 
intent.putInt("key4", v4); 

但是,它似乎只對key1值保留在這兩種情況下(使用捆綁時,它顯然只包含1鍵)。我錯過了什麼?

編輯:這是我如何檢索Receiver值:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_video); 

    Intent intent = getIntent(); 
    Bundle bundle = intent.getExtras(); 
    v1 = bundle.getInt("key1", DEFAULT1); 
    v2 = bundle.getString("key2", "DEFAULT2"); 
    v3 = bundle.getString("key3", "DEFAULT3"); 
    v4 = bundle.getInt("key4", DEFAULT4); 

    // ... 
} 

或者:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_video); 

    Intent intent = getIntent(); 
    v1 = intent.getIntExtra("key1", DEFAULT1); 
    v2 = intent.getStringExtra("key2"); 
    v3 = intent.getStringExtra("key3"); 
    v4 = intent.getIntExtra("key4", DEFAULT2); 

    // ... 
} 

當我打印出來的v1v2v3v4值, v1是唯一一個非空/非默認值(我最初放在中的值- 實際上,我最初放入Intent的所有值都是非默認值)。

編輯2:

我嘗試使用像這樣:

intent.putExtra("bundle", bundle); 

然後在Receiver

Bundle bundle = intent.getBundleExtra("bundle"); 

然而,bundle爲空。

編輯3:

改變其值放入/從意向檢索似乎並不影響任何東西的順序。也沒有指定Bundle的容量。如果有幫助,這個意圖在PendingIntent中使用。

+0

「但是,似乎只有key1的值在兩種情況下都保留了」 - 您如何確定這一點? – CommonsWare

+0

你如何檢索值? – NehaK

+0

用代碼編輯我的問題 - 如果沒有Bundle,我只需使用'getExtras()'作爲Bundle和'getExtra'。此外,我打印出所有檢索到的值並將其與默認值進行比較。 – Technicolor

回答

0

原來我真的忽略了簡單的事情 - 在一個的PendingIntent用我的意圖解僱一個接收器,然後開始一個服務,但我忘記了將Bundle從原始意向轉移到最終由第二個Activity收到的(新的,不同的)Intent Ÿ服務)。這個問題現在已經解決了。

0

您可以簡單地傳遞並接收Intent Extras而不使用Bundle。

SenderClass.java

Intent intent = new Intent(getApplicationContext(), Receiver.class); 
intent.putExtra("key1", key1); 
intent.putExtra("key2", key2); 
intent.putExtra("key3", key3); 
startActivity(intent) 

Receiver.java

String key1 = getIntent().getStringExtra("key1"); 
String key2 = getIntent().getStringExtra("key"); 
String key3 = getIntent().getStringExtra("key3"); 
+0

我已經試過了(代碼在我的問題中)。兩種方式都沒有奏效。 – Technicolor