Search code examples
androidandroid-sqliteandroid-cursor

CursorIndexOutOfBounds Exception: Index 0 requested, with a size of 0


I tried to read the SQLite database column and store each values in an String array. I did the following but it returned exception cursoroutofbounds. Help me figure out what I'm doing wrong?

 public String[] getPlaces(){
   SQLiteDatabase db = this.getReadableDatabase();

    String [] columns = {"place1"};
    c = db.query("rates_table", columns, null, null, null, null, null);
    String[] places = new String[c.getColumnCount()];
    c.moveToNext();

    for(int i=0; i<c.getColumnCount(); i++)
        places[i] = c.getString(i);

    return places;
}

Solution

  • I worked out for sometime and found out the solution:

     public String[] getPlaces(){
            SQLiteDatabase db = this.getReadableDatabase();
    
            String [] columns = {"place1"};
            c = db.query("rates_table", columns, null, null, null, null, null);
    
            c.moveToFirst();
            ArrayList<String> places = new ArrayList<String>();
            while(!c.isAfterLast()) {
                places.add(c.getString(c.getColumnIndex("place1")));
                c.moveToNext();
            }
            c.close();
            return places.toArray(new String[places.size()]);
    
        }