如何为Android应用程序按降序排列我的SQLITE数据库?


67

以降序显示数据的最有效方法是什么?

public String getRank() {

    String[] rank = new String[]{ KEY_ROWID };
    Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, null);   //reading information from db.
    String rankResult = "";

    int iRow = c.getColumnIndex(KEY_ROWID); //Cursor looking for column setting equal to these ints.


    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { 
        //Move to first row - where cursor starts and moves to next row as long it is not after last row.
        rankResult = rankResult + c.getString(iRow) + "\n"; 
        //Returning value of row that it is currently on.
    }
    return rankResult;  //returning result
}

public String getName() {

    String[] name = new String[]{ KEY_NAME };
    Cursor c = scoreDb.query(DATABASE_TABLE, name, null, null, null, null, null);   //reading information from db.
    String nameResult = "";

    int iRow1 = c.getColumnIndex(KEY_NAME); //Cursor looking for column setting equal to these ints.


    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { 
        //Move to first row - where cursor starts and moves to next row as long it is not after last row.
        nameResult = nameResult + c.getString(iRow1) + "\n"; 
        //Returning value of row that it is currently on.
    }
    return nameResult;  //returning result
}

public String getScore() {

    String[] score = new String[]{ KEY_SCORE };
    Cursor c = scoreDb.query(DATABASE_TABLE, score, null, null, null,null, null);   //reading information from db.
    String scoreResult = "";

    int iRow2 = c.getColumnIndex(KEY_SCORE); //Cursor looking for column setting equal to these ints.


    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { 
        //Move to first row - where cursor starts and moves to next row as long it is not after last row.
        scoreResult = scoreResult + c.getString(iRow2) + "\n"; 
        //Returning value of row that it is currently on.
    }
    return scoreResult; //returning result
}

Answers:


186

查询有两种语法,您正在使用的语法,最后一列表示orderBy,您只需要指定要在哪一列上执行orderBy +“ ASC”(或)orderBy +“ DESC”

Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC"); 

请参考文档以了解有关query()方法的更多信息。


我想按得分列排序,所以我是否必须将其仅放在得分列或其他两个列中?
卡拉·德西

只是分数栏就足够了。
科萨2012年

在仿真器中出现强制关闭错误..是因为我对三个不同的列有三种不同的方法吗?
卡拉·德西

public String getScore(){String [] score = new String [] {KEY_SCORE}; 游标c = scoreDb.query(DATABASE_TABLE,score,null,null,null,null,null,score +“ DESC”); 字符串scoreResult =“”; int iRow2 = c.getColumnIndex(KEY_SCORE); //光标寻找与这些整数相等的列设置。for(c.moveToFirst();!c.isAfterLast(); c.moveToNext()){scoreResult = scoreResult + c.getString(iRow2)+“ \ n”; //返回当前所在行的值。} return scoreResult; }
Carla Dessi 2012年

1
@kosa是否有任何方法可以防止对该字符串进行硬编码,例如是否存在任何最终常量?
CopsOnRoad

13
Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");

尝试这个


6
您只复制了评分最高且被接受的答案。
goetzc

13
return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
                         " ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
                         , new String[] {});

1
但是如何将排序后的更改保存到原始表中呢?
pranjal khanduri

6

根据文档

public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);

并且您的ORDER BY参数意味着:

如何对行进行排序,格式为SQL ORDER BY子句(不包括ORDER BY本身)。传递null将使用默认的排序顺序,该顺序可能是无序的。

因此,您的查询将是:

 Cursor cursor = db.query(TABLE_NAME, null, null,
            null, null, null, KEY_ITEM + " DESC", null);

5
public List getExpensesList(){
    SQLiteDatabase db = this.getWritableDatabase();

    List<String> expenses_list = new ArrayList<String>();
    String selectQuery = "SELECT * FROM " + TABLE_NAME ;

    Cursor cursor = db.rawQuery(selectQuery, null);
    try{
        if (cursor.moveToLast()) {

            do{
                String info = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION));
                expenses_list.add(info);
            }while (cursor.moveToPrevious());
        }
    }finally{
        cursor.close();
    }
    return expenses_list;
}

这是我从数据库中读取记录以降序排列的方式。提取每个记录后,将光标移至最后一个并移至上一个记录。希望这会有所帮助〜


3
Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});

这对我有用!!!


Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CHAL + " ORDER BY date(" + KEY_FORMATTED_DATE + ") ASC", null);其中,KEY_FORMATTED_DATEYYYY-MM-DD格式,但它不工作。stackoverflow.com/questions/40129782/…–
Si8

2

你可以做到这一点

Cursor cursor = database.query(
            TABLE_NAME,
            YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");

2

SQLite ORDER BY子句用于根据一个或多个列以升序或降序对数据进行排序。游标c = scoreDb.query(DATABASE_TABLE,rank,null,null,null,null,yourColumn +“ DESC”);

SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(
            TABLE_NAME,
            rank,
            null,
            null,
            null,
            null,
            COLUMN + " DESC",
            null);

1

我们还有一个选项可以通过

public Cursor getlistbyrank(String rank) {
        try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
        } catch (SQLException sqle) {
            Log.e("Exception on query:-", "" + sqle.getMessage());
            return null;
        }
    }

您可以使用这两种方法订购


0

关于有效的方法。您可以使用CursorLoader。例如,我包括了我的行动。而且,您必须为数据库实现ContentProvider。https://developer.android.com/reference/android/content/ContentProvider.html

如果实施此方法,则将非常高效地称为数据库。

public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {

   public interface OnLoadEntities {
       void onSuccessLoadEntities(List<Entities> entitiesList);
   }

    private OnLoadEntities onLoadEntities;

    private final Context context;

    private final LoaderManager loaderManager;

    public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
        this.context = context;
        this.loaderManager = loaderManager;
    }

    public void setCallback(OnLoadEntities onLoadEntities) {
        this.onLoadEntities = onLoadEntities;
    }

    public void loadEntities() {
        loaderManager.initLoader(LOADER_ID, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

0

这太可怕了!花了我几个小时!这是我的表行:

private String USER_ID = "user_id";
private String REMEMBER_UN = "remember_un";
private String REMEMBER_PWD = "remember_pwd";
private String HEAD_URL = "head_url";
private String USER_NAME = "user_name";
private String USER_PPU = "user_ppu";
private String CURRENT_TIME = "current_time";

Cursor c = db.rawQuery("SELECT * FROM " + TABLE +" ORDER BY " + CURRENT_TIME + " DESC",null);

每次更新表时,都会更新CURRENT_TIME进行排序。但是我发现这是行不通的。结果没有按我想要的排序。最后,我发现列“ current_time”是sqlite的默认行。

解决方法是,将列“ cur_time”重命名,而不是“ current_time”。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.