如何根据具体情况检索单行?

时间:2015-12-11 04:30:54

标签: android

这里是我的编码: - DatabaseHelper.java

public Cursor getinnformationUser(SQLiteDatabase db) {
    String a1="f1";
    Cursor cursor;
    String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
    String selection = Menu.NewMenuInfo.MENU_ID + "=" + a1;
    cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,null);
    return cursor;
}

Menu1.java

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menuset1);
    s_id = (TextView) findViewById(R.id.idSet1);
    s_name = (TextView) findViewById(R.id.nameSet1);
    s_drink = (TextView) findViewById(R.id.drinkSet1);
    s_price = (TextView) findViewById(R.id.priceSet1);
    set1 = (Button) findViewById(R.id.buttonOrderSet);
    userDbHelper = new UserDbHelper(getApplicationContext());
    sqLiteDatabase = userDbHelper.getReadableDatabase();
    cursor = userDbHelper.getinnformationSet1(sqLiteDatabase);
    if (cursor != null){
        cursor.moveToFirst();
            String id = cursor.getString(0);
            String name = cursor.getString(1);
            String drink = cursor.getString(2);
            String price = cursor.getString(3);
            s_id.setText(id);
            s_name.setText(name);
            s_drink.setText(drink);
            s_price.setText(price);
        }
}
}

基本上我想根据id =“f1”显示id,名称,饮料,价格。 例如:如果id =“f1”,则显示所有信息,而不使用任何搜索或单击按钮。

当我运行此编码时,应用程序已停止

3 个答案:

答案 0 :(得分:0)

您需要将选择参数作为数组传递,但在选择字符串中,您应该将?标记。像这样更改getinnformationUser方法:

public Cursor getinnformationUser(SQLiteDatabase db) {
    String a1="f1";
    Cursor cursor;
    String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
    String selection = Menu.NewMenuInfo.MENU_ID + "= ?";
    String[] selectionArgs = new String[] {a1};
    cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,selectionArgs,null,null,null,null);
    return cursor;
}

您可以详细了解查询方法here

答案 1 :(得分:0)

基本上你的选择查询是错误的......如下所示

public Cursor getinnformationUser(SQLiteDatabase db) {
    String a1="f1";
    Cursor cursor;
    String[] projections = {Menu.NewMenuInfo.MENU_ID, Menu.NewMenuInfo.MENU_NAME, Menu.NewMenuInfo.MENU_PRICE};
    String whereclause = Menu.NewMenuInfo.MENU_ID + "= ?";
    String where_args[] = {a1};

    cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,whereclause,where_args,null,null,null);
    return cursor;
}

完美的工作......

答案 2 :(得分:0)

使用 orderBy 。在orderBy传递任何值以对行进行排序,例如,如果您想按ID排序,则传递id并添加limit 1

cursor=db.query(Menu.NewMenuInfo.TABLE_NAME,projections,selection,null,null,null,"id limit 1");

这将只选择一行。

<强>校正 您也可以使用query()(Eric B.提供的链接)将限制作为参数传递