从SQLiteDatabase检索数据并将其显示在新活动中

时间:2012-05-31 05:24:00

标签: android database sqlite android-listview data-retrieval

我可以在ListView中的SQLiteDatabase填充我的lunch.java个项目。现在我想点击一个项目(ListView内的总共8个项目)并转到一个名为Display.java的新活动,并显示它的所有营养成分。

编辑后

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); 

}

1 个答案:

答案 0 :(得分: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);
}