For simplicity, lets say I have the following class object and DB classes in my Android app:
public class MyObject{
private String title;
private double number;
}
public class MyObjectDB extends SQLiteOpenHelper {
public static final String COL_1 = "ID";
public static final String COL_2 = "TITLE";
public static final String COL_3 = "NUMBER";
Typically examples just use the following to return a Cursor object from the DB class, and then the Cursor is used within the Activity etc..
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("select * from "+TABLE_NAME,null);
}
For small data sets is there a reason not to just initialize and return an ArrayList of class objects directly from the DB class, assuming I need the list even if empty?
public ArrayList<MyObject> getMyObjectList(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
ArrayList<MyObject> list = new ArrayList<>();
if(res.getCount()!=0){
res.moveToFirst();
while (!res.isAfterLast()){
MyObject myObj = new MyObject();
myObj.setTitle(res.getString(1));
myObj.setNumber(res.getDouble(2));
list.add(myObj);
res.moveToNext();
}
}
res.close();
return list;
}
I'm just trying to determine if there is a reason all of the examples always return a Cursor, which then has to be used from within the calling Activity to initialize a list. The code within the Activity is much cleaner if it can directly call a method to return the list it needs, rather than having to perform the exact same logic from within the Activity.
This was the only somewhat similar question I found on the topic: Object oriented design with database (java): cursors, SQLiteOpenHelper
Edit: An additional thought on why it could be better to return a Cursor rather than the ArrayList -- In my admittedly limited knowledge of this, it seems that the lifetime of a Cursor object in memory is very well defined and is released when you call cursor.close(). In contrast, if you initialize and return a list of class objects, and then directly assign that to a field in the calling class, then the returned object may not be released from memory since you are holding the reference. I suppose my question remains, whether it makes a performance difference if your intention is to hold an ArrayList representing all of that data regardless. Maybe there are other caveats to account for since when returning the new ArrayList you are assigning a reference to a new List, rather than directly modifying the one you initially declared as you would if you had returned a Cursor. --I admittedly know little about how this works in Java (my reason for asking this), so I apologize if there is any incorrect information here.