2013-01-11 72 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类方法的信息。

相关问题