Putting cursor data into an array
Asked Answered
G

5

5

Being new in Android, I am having trouble dealing with the following:

public String[] getContacts(){
    Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
    String [] names = {""};
    for(int i = 0; i < cursor.getCount(); i ++){
            names[i] = cursor.getString(i);
    }
    cursor.close();
    return names;
}

The following gives me the following error:

09-18 10:07:38.616: E/AndroidRuntime(28165): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sqllitetrial/com.example.sqllitetrial.InsideDB}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5

I am trying to extract the data inside the cursor to an array. Can someone help me with the implementation.

Granulocyte answered 18/9, 2013 at 4:24 Comment(2)
its better to use arraylist instead of string[] .Shelli
Help full link For u androidhive.info/2011/11/android-sqlite-database-tutorialAnkylostomiasis
P
14
names.add(cursor.getString(i));

"i" is not the cursor row index, it's the column index. A cursor is already positioned to a specific row. If you need to reposition your cursor. Use cursor.move or moveToXXXX (see documentation).

For getString/Int/Long etc. you just need to tell the cursor which column you want. If you don't know the columnIndex you can use cursor.getColumnIndex("yourColumnName").

Your loop should look like this:

public String[] getContacts(){
    Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
    cursor.moveToFirst();
    ArrayList<String> names = new ArrayList<String>();
    while(!cursor.isAfterLast()) {
        names.add(cursor.getString(cursor.getColumnIndex("name")));
        cursor.moveToNext();
    }
    cursor.close();
    return names.toArray(new String[names.size()]);
}
Pushup answered 18/9, 2013 at 4:51 Comment(3)
i forgot to call cursor.moveToNext() you might need to edit your code. see edit abovePushup
A couple of bugs: cursor.close(); and return names.toArray(new String[names.size()]); But thanks very much for the solution!Gershon
@Gershon thanks, I've edited it. I would be so lost without my IDE + autocomplete. On a side note, it's probably a good idea to wrap the whole thing in a try/catch and put cursor.close() into the finally block.Pushup
S
5

I hope its useful to you.

 public static ArrayList<ModelAgents> SelectAll(DbHelper dbaConnection) {
            ArrayList<ModelAgents> Agents_aList = new ArrayList<ModelAgents>();

            SQLiteDatabase sqldb = dbaConnection.openDataBase();
            Cursor cursor = sqldb.rawQuery("SELECT * FROM Agents", null);
            if (cursor != null)// If Cursordepot is null then do
                                // nothing
            {
                if (cursor.moveToFirst()) {


                    do {
                        // Set agents information in model.
                        ModelAgents Agents = new ModelAgents();
                        Agents.setID(cursor.getInt(cursor
                                .getColumnIndex(TblAgents.ID)));
                        Agents.setCode(cursor.getString(cursor
                                .getColumnIndex(TblAgents.CODE)));
                        Agents.setName(cursor.getString(cursor
                                .getColumnIndex(TblAgents.NAME)));

                        Agents_aList.add(Agents);
                    } while (cursor.moveToNext());
                }
                cursor.close();
            }

            sqldb.close();

            return Agents_aList;

        }
Shelli answered 18/9, 2013 at 4:27 Comment(1)
Can you post the ModelAgents Class?Fanfani
T
3

When cursor is returned from a database query it is placed at index -1 that is above the first entry of the cursor so, before using the cursor to get data you have move it to its first position. For that add cursor.MoveToFirst(); after Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);

Travis answered 18/9, 2013 at 4:41 Comment(0)
W
2

use this:

if (cursor != null && cursor.getCount()>0){
  cursor.moveToFirst();
  do{
    for(int i = 0; i < cursor.getCount(); i ++){
      names.add(cursor.getString(i));
    }
  }while(cursor.moveToNext());
}

cursor.close();
Wallsend answered 18/9, 2013 at 4:45 Comment(1)
I made a small change in the code, because there was a syntax error. Besides, instead of using 'cursor.getCount();', you should be using amount of columns.Pear
F
1

Try to put the data into the ArrayList<String> as below:

   public ArrayList<String> getContacts(){
        Cursor cursor = getReadableDatabase().rawQuery("SELECT name FROM contacts", null);
        ArrayList<String> names=new ArrayList<String>();
        if (cursor != null)
        {
            if (cursor.moveToFirst()) {
                for(int i = 0; i < cursor.getCount(); i ++){
                      names.add(cursor.getString(i));
                   }
               }
       cursor.close();
     }
     return names;
  }
Fungoid answered 18/9, 2013 at 4:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.