user6891645 user6891645 - 2 months ago 15
Android Question

How to sort data from Database with DESC in Android

I want load data from

SQLiteDatabase
and I should sort this data with DESC!

I write below code:

/*Retrieve data from database*/
public List<FavModel> getFavList() {

// 1. initialize modelList
List<FavModel> modelList = new ArrayList<>();
// 2. select
String QUERY_SELECT = "SELECT * FROM " + FavContract.favInfo.TABLE_NAME;
// 3. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 4. read from query
Cursor cursor = db.rawQuery(QUERY_SELECT, null);
// 5. set model data into modelList
if (cursor.moveToFirst()) {
do {
FavModel model = new FavModel();
model.setTitle(cursor.getString(1));
model.setImage(cursor.getString(2));
model.setContent(cursor.getString(3));
model.setDate(cursor.getString(4));
model.setAuthor(cursor.getString(5));
model.setCategory(cursor.getString(6));

modelList.add(model);

} while (cursor.moveToNext());
}
// 6. return modelList
return modelList;
}


In my code, when added new item show me below of age items, but I want when added new item show me top ago items.

My mean is when added new items sort by DESC, not sort ASC.

How can I it?

Answer

if you have a specific column like id then do like

String QUERY_SELECT = "SELECT * FROM " + FavContract.favInfo.TABLE_NAME + " ORDER BY " + column_name + " DESC" ;
Comments