2013-01-11 39 views
1

我試圖將從我的列表視圖中點擊數據的ID傳遞給第二類中的新活動,即我單擊listview上的項目。調用onListItemClick方法並啓動一個新的意圖。 id與i.getExtra中的對象一起傳遞。然後將id存儲到第二個類中的一個新變量中,以備後用。通過意圖傳遞一個ID

我已經盡力瞭解如何傳遞id,但似乎無法解決如何將它存儲在第二課的新變量中。

繼承人我的代碼:

public void onListItemClick(ListView list, View v, int list_posistion, long item_id) 
{ 


    long id = item_id; 
    Intent i = new Intent("com.example.sqliteexample.SQLView"); 
    i.putExtra(null, id); 
    startActivity(i); 
} 

誰能告訴我如何引用它在第二類?

回答

0

您需要從Intent獲取Bundle,然後確保獲得...以獲取特定元素。

Bundle extras = getIntent().getExtras(); 
String id; 

if (extras != null) { 
    id= extras.getString("key"); //key should be what ever used in invoker. 
} 

有一件事令人驚訝的是爲什麼你正在使用null關鍵?我會避免使用保留字,而是使用正確的名稱,比如userID等,

0
Intent intent = new Intent("com.example.sqliteexample.SQLView"); 
        Bundle bundle = new Bundle(); 
        bundle.putString("position", v.getTag().toString()); 
        intent.putExtras(bundle); 
        context.startActivity(intent); 

在第二類

Bundle intent= getIntent().getExtras(); 

     if (intent.getExtras() == null) { 
    id= intent.getString("position"); 
    } 

希望這有助於

0

這是非常簡單的。
只要改變:

i.putExtra(null, id); 

有:

i.putExtra("myId", id); 

,並在第二次活動只需使用:

Bundle extras = getIntent().getExtras(); 
if (extras != null) { 
    String value = extras.getInt("myId"); 
} 
0

Intent.putExtra()第一個參數是用來識別您的額外一個String鍵。而不是i.putExtra(null, id)嘗試i.putExtra("SomeString", id)

然後,在(或內的任何地方),你的第二個活動的onCreate,你可以從像這樣的意圖得到你的ID後面:

Intent intent = getIntent(); 
long id = intent.getLongExtra("SomeString"); 

也有用於獲取字符串,字符數,布爾方法, Ints和更復雜的數據結構。請點擊這裏:http://developer.android.com/reference/android/content/Intent.html獲取更多關於Intent類方法的信息。