-2

This snippet of code I try to retrieve all the rows of the notes table but during the execution returns the number of rows are correct but all are like the last row .. I want to know what the error

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;
}
amralsaidy
  • 183
  • 1
  • 15
  • move your Note note=new Note(); to inside while loop. All the contents of the list are referring to same object . – Jimmy Oct 24 '17 at 21:28
  • 2
    Possible duplicate of [Why does my ArrayList contain N copies of the last item added to the list?](https://stackoverflow.com/questions/19843506/why-does-my-arraylist-contain-n-copies-of-the-last-item-added-to-the-list) – Shaishav Jogani Oct 24 '17 at 22:03

2 Answers2

0

Move Note note = new Note(); just after while (cursor.moveToNext()) {.

Though this is not the place to ask "why my code doesn't work?"

Yusef Maali
  • 2,201
  • 2
  • 23
  • 29
  • thanks my brother .. it work with me but i don't understand your "Though this is not the place to ask "why my code doesn't work?"" what the correct place ?!!! – amralsaidy Oct 24 '17 at 21:36
  • sorry friend, my fault. As written here https://stackoverflow.com/help/on-topic your question is perfectly legit and well-formed. – Yusef Maali Oct 24 '17 at 21:54
0

just move your Note initializing in the loop and also try to use

`

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

`

before accesing cursor , as with your code you will not have the first data from cursor,as it's already moving to the next.

himel
  • 500
  • 5
  • 14