How to get data from database to arraylist and show them

Viewed 57

I am trying to get data from database to arraylist and then show them. Unfortunately I get this

error:java.lang.OutOfMemoryError: OutOfMemoryError

thrown while trying to throw an exception; no stack trace available. I am using own class for Object, which are store in database.

MainActivity code:

narodyList = db.getVsechnyNarody(); 
String k = narodyList.get(1).toString();
Toast.makeText(getApplicationContext(),"Záznam" + k,Toast.LENGTH_LONG).show();

DatabaseHandler.java:

 public List<Narody> getVsechnyNarody(){
        List<Narody> narodyList = new ArrayList<Narody>();
        String selectQuery = "SELECT  * FROM " + TABLE_NARODY;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if(cursor.moveToFirst()){
            do {
                Narody narod = new Narody();
                narod.setId(Integer.parseInt(cursor.getString(0)));
                narod.setNazevNaroda(cursor.getString(1));
                narodyList.add(narod);
            } while (cursor.moveToFirst());
        }
        cursor.close();
        db.close();
        return narodyList;
    }
1 Answers

The mistake is probably on line 13.

This line keeps you stuck in infinite loop (you are moving to first row every time the loop is executed):

} while (cursor.moveToFirst());

Replace it with this line:

} while (cursor.moveToNext());

I hope this helped

Related