如何从SQLite返回具有相同值的多个条目

时间:2012-09-12 20:52:54

标签: android database sqlite

My database

这就是我的数据库的样子,如何返回KEY_ALCOHOL列中具有相同字符串的所有行?在我获得所有行之后,我需要随机选择一行然后显示它。

我试过这个: DATABASE HELPER .JAVA

public Cursor getAlcohol(String alcohol) throws SQLException 
{
    Cursor mCursor =
            myDataBase.query(true, DB_TABLE, new String[] {
                    KEY_ROWID,
                    KEY_ALCOHOL, 
                    KEY_TYPE,
                    KEY_BRAND,
                    KEY_PRICE
                    }, 
                    KEY_ALCOHOL + "=" + alcohol, 
                    null,
                    null, 
                    null, 
                    null, 
                    null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

主要活动.JAVA

myDbHelper.openDataBase();
    Cursor c = myDbHelper.getAlcohol("Liquor");
    if (c.moveToFirst())
    {
        do {          
            DisplayTitle(c);
        } while (c.moveToNext());
    }
    myDbHelper.close();

}

public void DisplayTitle(Cursor c)
{
    Toast.makeText(this, 
            "id: " + c.getString(0) + "\n" +
            "ALCOHOL: " + c.getString(1) + "\n" +
            "TYPE: " + c.getString(2) + "\n" +
            "BRAND:  " + c.getString(3) + "\n" +
            "PRICE:  " + c.getString(4),
            Toast.LENGTH_LONG).show();        
} 

我正在测试看看这是否只会在KEY_ALCOHOL列中返回所有带“Liquor”的行,而是它给了我一个空指针。

修改

搞定了! 这是我想出来的,它的工作原理!如果出现任何问题或让您看到更好的方法,请告诉我!谢谢大家!

myDbHelper.openDataBase();
     Cursor Test = myDbHelper.getAlcohol("Liquor");
     int test7 = Test.getCount();
     test9 = r.nextInt(test7);
     Cursor c = myDbHelper.getTitle(test9);
     if (c.moveToFirst())        
         DisplayTitle(c);
     else
         Toast.makeText(this, "No title found", 
                Toast.LENGTH_LONG).show();
    myDbHelper.close();

1 个答案:

答案 0 :(得分:1)

我希望这有效

public Cursor getAlcohol(String alcohol) throws SQLException 
{
    Cursor mCursor =
            myDataBase.query(true, DB_TABLE, new String[] {
                    KEY_ROWID,
                    KEY_ALCOHOL, 
                    KEY_TYPE,
                    KEY_BRAND,
                    KEY_PRICE
                    }, 
                    KEY_ALCOHOL + "=?", 
                    new String[] { alcohol },
                    null, 
                    null, 
                    null, 
                    null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

看结构

 Cursor SQLiteDatabase.query(String table, 
 String[] columns,
 String selection,
 String[] selectionArgs,
 String groupBy,
 String having,
 String orderBy,
 String limit)

你的“选择”是错误的。由于参数是分开的,因此导致WHERE KEY_ALCOHOL + "=" + alcohol = null