(已编辑)在SQLiteOpenHelper for Android

时间:2016-01-14 07:56:19

标签: java android spinner sqliteopenhelper

我是Java Coding的初学者,这是我第一次在Android中使用SQLiteOpenHelper。我有问题使用MainActivity中输入的颜色从表中检索水果。

在应用程序中,有2个字段。 1.颜色 2.水果

例如,如果用户输入:colors - red&水果 - 草莓

旋转器会显示草莓。但与此同时,旋转器应该包含之前根据颜色输入的水果:红色。

以下是我的代码的片段。请建议我做什么。谢谢。

MainActivity

btnAdd.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            String fruits= inputFruits.getText().toString();
            String colours= inputColours.getText().toString();

            if (fruits.trim().length() > 0) {
                // database handler
                DatabaseHandler db = new DatabaseHandler(
                      getApplicationContext());


                // inserting new label into database
                db.insertLabel(fruits, colours);

                // making input filed text to blank
                inputFruits.setText("");


                // Hiding the keyboard
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                // loading spinner with newly added data
                loadSpinnerData();
            } else {
                Toast.makeText(getApplicationContext(), "Please enter label name",
                        Toast.LENGTH_SHORT).show();
            }

        }
    });

SQLiteOpenHelper

public void insertLabel(String fruits, String colours){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_FRUITS, fruits); 
    values.put(KEY_COLOURS, colours); 

    // Inserting Row
    db.insert(TABLE_LABELS, null, values);
    db.close(); // Closing database connection
}


public List<String> getAllLabels(){
    List<String> labels = new ArrayList<String>();

    // Select All Query
    String selectQuery = "SELECT" + KEY_FRUITS + "FROM" + TABLE_LABELS + " WHERE COLOURS = " + KEY_COLOURS;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            labels.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }

3 个答案:

答案 0 :(得分:1)

SELECT之后和之前需要空间。在FROM之后。如果它是Varchar(我猜它是),KEY_COLOURS应该是单引号。

String selectQuery = "SELECT " + KEY_FRUITS + " FROM " + TABLE_LABELS + " WHERE COLOURS = '" + KEY_COLOURS + "'";

如果要检索与水果标签或颜色或两者匹配的行,则查询可能如下:

String selectQuery = "SELECT " + KEY_FRUITS + " FROM " + TABLE_LABELS + " WHERE COLOURS = '" + KEY_COLOURS + "' or FRUITS='" + KEY_FRUITS + "'";

答案 1 :(得分:0)

尝试添加&#34;;&#34;在句末。

String selectQuery = "SELECT" + KEY_FRUITS + "FROM" + TABLE_LABELS + " WHERE COLOURS = " + KEY_COLOURS + ";";

答案 2 :(得分:0)

试试这个

Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE "+ COLOURS +" = ?", new String[]{KEY_COLOURS} );