2012-05-31 16 views
0

我可以在我的SQLiteDatabaselunch.java中填充我的ListView项。现在我想点击一个项目(ListView内的8个项目),然后转到名为Display.java的新活动,并显示它的所有营养成分。从SQLiteDatabase中检索数据并将其显示在新活动中

编辑后

lunch.java:

public void onItemClick(AdapterView<?> parent, View v, int pos, long id) { 
    switch(pos) 

    { 
    case 0 : 
     String mealName = (String) parent.getItemAtPosition(pos); 
     Cursor cursor = dbopener.getBreakfastDetails(mealName); 
     cursor.moveToNext(); 
     id = cursor.getLong(cursor.getColumnIndex(mealName)); 
     String message = cursor.getString(1) + "\n" + cursor.getInt(2); 
     Intent event1 = new Intent("com.edu.tp.iit.mns.Display"); 
     event1.putExtra("name", id); 
     startActivity(event1); 
     break; 

Display.java

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

     TextView tv = (TextView) findViewById(R.id.tvfoodName);  


     Intent intent = getIntent(); 
     long id = intent.getLongExtra("name", -1); 
     if(id == -1){ 
      return; 
     } 

     tv.setText(-1); 

} 

回答

5

onItemcClick你已经拥有的元素的id那被点击,参数为id。用它来识别物品在你的下一个活动:

public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {  
    Intent newActivity = new Intent("com.edu.tp.iit.mns.Display"); 
    newActivity.putExtra("the_key", id); 
    startActivity(newActivity); 
} 
Display活动

然后获取长期价值,并从数据库中获取对应于id数据:

Intent newActivity = getIntent(); 
long id = newActivity.getLongExtras("the_key", -1); 
if (id == -1) { 
    //something has gone wrong or the activity is not started by the launch activity 
    return 
} 
//then query the database and get the data corresponding to the item with the id above 

上面的代码会适用于基于Cursor的适配器的情况。但是您可能使用基于列表的适配器(因为getItemAtPosition(pos)返回String而不是Cursor)。在这种情况下,我会做getLunchDetails方法返回餐名称的唯一id并传递到Details活动:

public void onItemClick(AdapterView<?> parent, View v, int pos, long id) { 
    String mealName = (String)parent.getItemAtPosition(pos); 
    Cursor cursor = dbopener.getLunchDetails(mealName); 
    cursor.moveToNext(); 
    long id = cursor.getLong(cursor.getColumnIndex("the name of the id column(probably _id")); 
    Intent newActivity = new Intent("com.edu.tp.iit.mns.Display"); 
    newActivity.putExtra("the_key", id); 
    startActivity(newActivity); 
} 
+0

请不要垃圾邮件的问题。请检查您的收件箱,并请将您在此处做出的第一条评论删除至我的回答。 – Luksprog

+0

谢谢你的帮助。非常感激 – Riyas2329

相关问题