Android - load values ​​from sqlite database to arraylist

I am new to android. I have an application working with SQLite DB. I need to move values ​​from a database to an arraylist of type object. The code used here is below.

private ArrayList<objectname> objectList = new ArrayList<objectname>(); //function used to get values from database public ArrayList<objectname> getResults() { MyDb db = new MyDb(this); //my database helper file db.open(); Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file if (c.moveToFirst()) { do { String date = c.getString(c.getColumnIndex("date")); try { ob = new objectname(); ob.setDate(c.getString(c.getColumnIndex("date")));// setDate function is written in Class file objectList.add(ob); } catch (Exception e) { Log.e(MY_DEBUG_TAG, "Error " + e.toString()); } } while (c.moveToNext()); } db.close(); return objectList; } 

This is not working properly. No errors were indicated, but I did not get the value in the objectList arraylist

Please help me .. Thanks in advance.

+6
android arraylist sqlite
source share
3 answers

try the following:

 private ArrayList<objectname> objectList = getResults(); private ArrayList<objectname> getResults() { MyDb db = new MyDb(this); //my database helper file db.open(); ArrayList<objectname> resultList = new ArrayList<objectname>(); Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file while (c.moveToNext()) { String date = c.getString(c.getColumnIndex("date")); try { ob = new objectname(); ob.setDate(date);// setDate function is written in Class file resultList.add(ob); } catch (Exception e) { Log.e(MY_DEBUG_TAG, "Error " + e.toString()); } } c.close(); db.close(); return resultList; } 
+7
source share

I had a similar problem with fetching values ​​from db using cursors and displaying on screen. The solution below works for me.

  Cursor cur = db.getAllValues(); int index = c.getColumnIndex("date"); cur.moveToFirst(); while (cur.isAfterLast() == false) { System.out.println(cur.getString(index)); // For debug purposes String date = cur.getString(index); try { ob = new objectname(); ob.setDate(date); resultList.add(ob); } catch (Exception e) { Log.e(MY_DEBUG_TAG, "Error " + e.toString()); } cur.moveToNext(); } cur.close(); 
+2
source share

Your query probably draws a space, and moveToFirst returns false.

How to write c.getCount() before an if ?

+1
source share

All Articles