【问题标题】:SQLite, return data as an arraySQLite,以数组形式返回数据
【发布时间】:2017-04-04 00:22:24
【问题描述】:

我的 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 开发人员的资料,但我似乎无法得到任何工作。

提前致谢

【问题讨论】:

  • col -1 表示您的Cursor 中没有"notes" 列。确定不只是"note"?为什么不直接使用用于创建表的NOTE
  • 是的,我很笨,但是它似乎只显示 0,而不是存储的字符串。有什么想法吗?
  • 如果您在该列中存储了String,为什么要使用getInt() 来检索值?使用getString()
  • 我不能感谢你,伙计,我已经坚持了好几个小时了,这真是太愚蠢了。谢谢分配伙伴。
  • 它只是我想象中的纯文本,所以你只需要notes.add(cursor.getString(cursor.getColumnIndex("NOTE"));

标签: java android arrays sqlite


【解决方案1】:

因为您只从数据库中获取整数和字符串,而不是使用 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();

【讨论】:

    【解决方案2】:

    检查“NOTE”的值,并将其用于: 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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      相关资源
      最近更新 更多