无法将数据库中的项目添加到列表中

时间:2016-08-09 06:39:01

标签: java android

我正在尝试将数据库中的一些项目添加到我的列表中,但是当我运行应用程序时,我看到该列表为空。

这就是我在列表中添加项目所做的工作

car_size = dbHelper.getSize("cars"); // getSize is a method that count items in database

Random random = new Random();
int cars_random = random.nextInt(car_size);

List<String> myList = dbHelper.read_added_names("cars"); // and this line should add items from database to the list

if(myList!= null && myList.size() > 0) {
        textView.setText(myList.get(truth_random));

        }else {
            Toast.makeText(activity.this, "" + myList.size(), Toast.LENGTH_SHORT).show();
        }  // here i can see that the size of my list is 0 and it's empty

我确定应该读取数据库的方法(这里我将其命名为read_aded_names)正常工作

public List<String> read_added_names (String subject){
    String selectQuery;
    List<String> list = new ArrayList<String>();
    if (subject.equals("*")) {
        selectQuery = "SELECT * FROM " + TABLE_NAME1;
    }else {
        selectQuery = "SELECT * FROM " + TABLE_NAME1 + " WHERE " + COLUMN_SUBJECT  + " = '" + subject+" '";
    }
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            list.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return list;
}

1 个答案:

答案 0 :(得分:0)

查询在主题变量之后包含空格,使其成为“汽车”而不是“汽车”。这可能是个问题。