【问题标题】:Retrieve data from SQLiteDatabase and display it in a new activity从 SQLiteDatabase 检索数据并将其显示在新活动中
【发布时间】:2012-06-05 08:55:04
【问题描述】:

我可以在lunch.java 中填充我的SQLiteDatabase 中的ListView 项目。现在我想点击一个项目(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); 

}

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 请不要向问题发送垃圾邮件。检查您的收件箱,请删除您在此处对我的回答所做的第一条评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2018-08-06
    • 2018-01-23
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多