【问题标题】:When selecting all rows from android sqlite database for an application, it is returning the last entry for all the entries当从 android sqlite 数据库中为应用程序选择所有行时,它会返回所有条目的最后一个条目
【发布时间】:2011-11-27 20:11:54
【问题描述】:

我目前正在开发一个安卓应用程序。我有一个 sqlite 数据库,它将文本(我只是在我的应用程序中用作字符串)存储在四列中。我正在尝试从表中返回所有行和列。我已经创建了数据并将其插入到表中,并使用 adb shell 中的 sqlite3 验证了它是否存在。我使用与我在程序中使用的语句相同的语句,它返回包含所有正确数据的所有行。在我的程序中,我通过遍历游标以ArrayList<ArrayList<String>> 格式存储所有数据。它返回与行相对应的正确数量的ArrayList<String>,但它们都只有最后一行的信息。这是我的代码:

private static final String SELECT = "SELECT * FROM " + TABLE_NAME;

public ArrayList<ArrayList<String>> allRecipes()
{
    ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
    ArrayList<String> recipe = new ArrayList<String>();
    Cursor cursor = db.rawQuery(SELECT, null);
    if(cursor.moveToFirst())
    {
        do
        {
            recipe.clear();
            recipe.add(cursor.getString(1));
            recipe.add(cursor.getString(2));
            recipe.add(cursor.getString(3));
            recipe.add(cursor.getString(4));
            results.add(recipe);
        }while(cursor.moveToNext());
        if(cursor != null && !cursor.isClosed())
            cursor.close();
    }
    return results;
}

然后,我在程序的另一部分中遍历 ArrayList,其中包含的所有信息只是输入到表中的最后一行的副本。我一收到它就在我的其他方法中检查了 ArrayLists,它们都是一样的,所以我假设它一定是这个代码段中的一个问题。我还尝试了带有 group by 和 order by 子句的 select 语句,但它仍然不起作用。使用带有正确参数的 db.query() 也会导致同样的问题。

【问题讨论】:

    标签: android sqlite select


    【解决方案1】:

    这是因为您在数组列表中添加了指向配方的链接,并在循环中的每次迭代中更改配方的值。

    你应该把代码改成这个

    public ArrayList<ArrayList<String>> allRecipes()
    {
       ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
       Cursor cursor = db.rawQuery(SELECT, null);
       if(cursor.moveToFirst())
       {
           do
           {
               ArrayList<String> recipe = new ArrayList<String>();
               recipe.add(cursor.getString(1));
               recipe.add(cursor.getString(2));
               recipe.add(cursor.getString(3));
               recipe.add(cursor.getString(4));
               results.add(recipe);
           }while(cursor.moveToNext());
           if(cursor != null && !cursor.isClosed())
              cursor.close();
       }
       return results;
    }
    

    【讨论】:

    • 最好定义类Recipe而不是使用数组列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2017-12-20
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    相关资源
    最近更新 更多