I'm working on an Android app that uses an SQLite database to load data into a list and display it. I have a DatabaseHelper class that deals with CRUD methods for the database. I'm trying to find specific results from a given date, however, although my query returns expected results and fills up a list to return, I can't get this list returned in my Main activity.
My query method:
public List<Earthquake>getListByDate(LocalDate dateInput){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + PUB_DATE + " = " + "'"+dateInput+"'", null);
Log.e("Cursor", ""+data.getColumnCount());
Log.e("QueryReturnList", ""+QueryReturnList(data));
return QueryReturnList(data);
}
Log:
E/Cursor: 12
E/returnList: [object, object, object...]
E/QueryReturnList: [object, object, object...]
QueryReturnList: (This method builds a list of objects from the input cursor)
private List<Earthquake>QueryReturnList(Cursor data){
List<Earthquake>returnList = new ArrayList<>();
int titleIndex = data.getColumnIndex(TITLE_COL),
descIndex = data.getColumnIndex(DESC_COL),
//... ;
while(data.moveToNext()){
Earthquake e = new Earthquake(
data.getString(titleIndex),
data.getString(descIndex),
//... ;
);
returnList.add(e);
}
Log.e("returnList",""+returnList);
return returnList;
}
Log:
E/returnList: [object, object, object...]
As I log these results, they work as expected in the DatabaseHelper. The correct results are found, and QueryReturnList returns the expected list object.
However, when I call this list from my main activity and set it to a new list, it appears to be empty when I log it (or debug).
List<Earthquake>earthquakes = mDatabaseHelper.getListByDate(currentDateSelection);
Log.e("earthquakesByDate", ""+earthquakes);
Log:
E/returnList: []
E/earthquakesByDate: []
Why am I getting an empty list returned when it does return and log a filled list initially (in my DatabaseHelper)?
Note: It seems to log "returnList" and "QueryReturnList" multiple times while running in an unexpected order. Are the methods not having time to get all the data and return?
This line:
Log.e("QueryReturnList", ""+QueryReturnList(data));
calls QueryReturnList(data)
, so after this has finished, the cursor is iterated and because of:
while(data.moveToNext())
the cursor's pointer is after the last row.
Then this:
return QueryReturnList(data);
calls again QueryReturnList(data)
and when it reaches this:
while(data.moveToNext())
it skips the loop because moveToNext()
returns false
.
So better drop this line:
Log.e("QueryReturnList", ""+QueryReturnList(data));
or rewrite getListByDate()
like this:
public List<Earthquake>getListByDate(LocalDate dateInput){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + PUB_DATE + " = " + "'"+dateInput+"'", null);
Log.e("Cursor", ""+data.getColumnCount());
List<Earthquake> list = QueryReturnList(data);
Log.e("QueryReturnList", ""+list);
return list;
}