0

我可以从我的 in 中填充我ListView的项目。现在我想点击一个项目(里面共有 8 个项目)并转到一个名为的新活动并显示它的所有营养成分。SQLiteDatabaselunch.javaListViewDisplay.java

编辑后

午餐.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;

显示.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); 

}
4

1 回答 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)返回 aString而不是 a 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);
}
于 2012-06-04T05:05:50.300 回答