0

我的数据库

这就是我的数据库的样子,我将如何返回 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();
4

1 回答 1

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因为论点是分开的。

于 2012-09-12T21:00:40.547 回答