SQLite,将数据作为数组返回

时间:2016-11-20 15:51:26

标签: java android arrays sqlite

我的Android应用程序中有一个SQLite数据库,结构如下:

public void onCreate(SQLiteDatabase db) {
  String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
                              "("+
                              _ID + " INTEGER PRIMARY KEY , " +
                              NOTE + " TEXT" +
                              ")";
  db.execSQL(CREATE_LISTS_TABLE);
}

这很有效,因为我可以毫无问题地将数据插入其中。但是我需要将音符存储在数组中。我目前有以下查询:

public List<String> getAllNotes() {
  List<String> notes = new ArrayList<>();

  String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;

  SQLiteDatabase db = getReadableDatabase();
  if(db!=null)
  {
     Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
     cursor.moveToFirst();
     while(!cursor.isAfterLast())
     {
       notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
       cursor.moveToNext();
     }
     cursor.close();
  }
  db.close();

  return notes;
}

但是,这会出现以下错误:

java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

我想知道如何解决这个问题,我已经阅读了android开发人员的东西,但我似乎无法得到任何工作。

提前致谢

2 个答案:

答案 0 :(得分:0)

检查“注意”的值,并将其用于: notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));

我认为拨打电话的最佳方式应该是这样的:

// Check the cursor
    if(cursor != null) {
        if (cursor.moveToFirst()) {
            // Variables to be used
            String note;

            // Col position
            int colNote = cursor.getColumnIndex(NOTE);

            do {
                // Get the information
                note = cursor.getString(colNote);

                // Add the note
                notes.add(note);
            } while (cursor.moveToNext());
        }

        // Close the cursor
        cursor.close();
    }

答案 1 :(得分:0)

因为您只从数据库中获取整数和字符串,而不是使用ArrayList,所以您可以尝试使用HashMap。因此,您只需提供密钥即可获得价值。下面的简单代码也适用于ArrayList,只需稍作修改。

试试这个

  HashMap<Integer,String> notes = new HashMap<Integer,String>() ;

        Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);

        while (cursor.moveToNext())

        {
            int i = cursor.getInt(0);
            String s = cursor.getString(1);
            notes.put (i,s) ;
        }

        cursor.close();
相关问题