Move cursor to row by one of the columns

Lior Iluz picture Lior Iluz · Nov 5, 2011 · Viewed 7k times · Source

After querying the data I wanted, I now have a cursor holding all the data, presented to the user in a Listview.

When a user clicks an item in order to edit it, I move the cursor to the right position cursor.moveToPosition(pos), from which I can get all the item's data I need: ID, Title, Folder or not, Parent folder.

Now that I have the Parent folder ID, how can I use it in order to get the title of the item's folder so I can show the user in what folder the item is currently in? I can't use move to position because I don't know the parent position, only its ID.

Here's an example of the db.

FOLDER column -> 0 = not a folder (false), 1 = a folder (true)

PARENT column -> holds the ID of its folder

ID  TITLE     FOLDER   PARENT
1   folder1      1        0
2   item1        0        1
3   item2        0        1
4   folder2      1        1
5   item1        0        4
6   item2        0        4
7   folder3      1        4
8   item1        0        7
9   item2        0        7

Example: User edits item3. I move the cursor to position 2 (starting from 0). I get item3 parent, which is ID=1. How can I get the TITLE of ID=1.

Hope it's clear enough :) Thank you!

Answer

Damian picture Damian · Nov 5, 2011

You can either loop through the cursor again checking each id to see if it is 1 and then get the title.

cur.moveToFirst();
while (cur.isAfterLast() == false) {
  if (cur.getInt(cur.columnIndex("ID") == 1) {
      String title = cur.getString(cur.columnIndex("TITLE"));
  }       
  cur.moveToNext();
}

Or you can issue a new query where id = 1.