【问题标题】:What the error in ArrayList add() method?ArrayList add() 方法中的错误是什么?
【发布时间】:2017-10-24 21:23:40
【问题描述】:

这个sn-p代码我尝试检索notes表的所有行,但在执行过程中返回的行数是正确的,但都像最后一行..我想知道错误是什么

public ArrayList<Note> selectAllNotes() {
    Cursor cursor = dbReader.rawQuery("SELECT * FROM notes", null);
    Note note = new Note();
    ArrayList<Note> notes = new ArrayList<>();
    while (cursor.moveToNext()) {
        note.setNoteID(cursor.getInt(cursor.getColumnIndex(DbHelper.ID)));
        note.setNoteTitle(cursor.getString(cursor.getColumnIndex(DbHelper.TITLE)));
        note.setNoteContent(cursor.getString(cursor.getColumnIndex(DbHelper.CONTENT)));
        notes.add(note);
    }
    return notes;
}

【问题讨论】:

标签: android arraylist add


【解决方案1】:

while (cursor.moveToNext()) { 之后移动Note note = new Note();

虽然这里不是问“为什么我的代码不起作用?”的地方

【讨论】:

  • 谢谢我的兄弟 .. 它对我有用,但我不明白你的“虽然这不是问“为什么我的代码不起作用?”的地方,正确的地方是什么?! !!
  • 对不起朋友,我的错。正如stackoverflow.com/help/on-topic 此处所写,您的问题完全合法且格式正确。
【解决方案2】:

只需在循环中移动您的 Note 初始化并尝试使用

`

if(cursor.getCount>0){
cursor.moveToFirst()
while(!cursor.isAfterLast()){
Note note=new Note();
....
}
}

`

在访问 cursor 之前,与您的代码一样,您不会从 cursor 获得第一个数据,因为它已经移动到下一个数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多