如何在Android中使用DESC对数据库进行排序

时间:2016-09-28 05:35:12

标签: android android-database

我想要从SQLiteDatabase加载数据,我应该使用 DESC 对这些数据进行排序!
我在下面写代码:

/*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;
}

在我的代码中,当添加新项目时显示我的年龄项目,但我想在添加新项目时显示我最前面的项目。
我的意思是添加新项目时按 DESC 排序,而不是排序 ASC

我该怎么办?

3 个答案:

答案 0 :(得分:1)

如果您有像id这样的特定列,那么就像

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

答案 1 :(得分:0)

"String QUERY_SELECT = SELECT * FROM " + FavContract.favInfo.TABLE_NAME + " ORDER BY " + col_name + " ASC";

答案 2 :(得分:0)

使用此查询语句

database.rawQuery("SELECT * FROM " + table name +
                         " ORDER BY " + date column name + " DESC"
                         , new String[] {});