对于android应用程序,我如何按降序排列我的SQLITE数据库?

时间:2023-01-11 01:14:53

What is the most efficient method of showing my data in descending order?

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

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
}

11 个解决方案

#1


160  

Query has two syntax, the syntax you are using, last column represents orderBy, you just need to specify on what column you want to do orderBy +"ASC" (or) orderBy +"DESC"

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

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

Refer this documentation to understand more about query() method.

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

#2


12  

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

Try this

试试这个

#3


10  

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

#4


4  

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

This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~

这是我从数据库中按降序读取列表视图的记录的方法。将光标移动到最后,并在获取每个记录后移动到先前的记录。希望这可以帮助~

#5


3  

According to docs:

根据文档:

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

and your ORDER BY param means:

而您通过param点餐的意思是:

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

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

So, your query will be:

因此,您的查询将是:

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

#6


3  

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

this works for me!!!

这适合我! ! !

#7


2  

you can do it with this

你可以用这个

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

#8


1  

We have one more option to do order by

我们还有一个选择

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

You can use this two method for order

您可以使用这两种方法进行排序

#9


0  

About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html

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

If you implement this, you will call you data base very efficient.

如果您实现了这一点,您将非常有效地调用您的数据库。

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) {
    }

#10


0  

This a terrible thing! It costs my a few hours! this is my table rows :

这一件可怕的事情!花了我几个小时!这是我的表格行:

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);

Every time when I update the table , I will update the CURRENT_TIME for sort. But I found that it is not work.The result is not sorted what I want. Finally, I found that, the column "current_time" is the default row of sqlite. The solution is, rename the column "cur_time" instead of "current_time".

每次更新表时,我都会更新CURRENT_TIME进行排序。但我发现这不是工作。结果不是我想要的排序。最后,我发现,“current_time”列是sqlite的默认行。解决方案是,将列重命名为“cur_time”,而不是“current_time”。

#11


0  

SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");

SQLite ORDER BY子句用于根据一个或多个列按升序或降序对数据进行排序。光标c = scoreDb。查询(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


160  

Query has two syntax, the syntax you are using, last column represents orderBy, you just need to specify on what column you want to do orderBy +"ASC" (or) orderBy +"DESC"

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

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

Refer this documentation to understand more about query() method.

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

#2


12  

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

Try this

试试这个

#3


10  

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

#4


4  

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

This is my way of reading the record from database for list view in descending order. Move the cursor to last and move to previous record after each record is fetched. Hope this helps~

这是我从数据库中按降序读取列表视图的记录的方法。将光标移动到最后,并在获取每个记录后移动到先前的记录。希望这可以帮助~

#5


3  

According to docs:

根据文档:

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

and your ORDER BY param means:

而您通过param点餐的意思是:

How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.

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

So, your query will be:

因此,您的查询将是:

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

#6


3  

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

this works for me!!!

这适合我! ! !

#7


2  

you can do it with this

你可以用这个

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

#8


1  

We have one more option to do order by

我们还有一个选择

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

You can use this two method for order

您可以使用这两种方法进行排序

#9


0  

About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html

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

If you implement this, you will call you data base very efficient.

如果您实现了这一点,您将非常有效地调用您的数据库。

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) {
    }

#10


0  

This a terrible thing! It costs my a few hours! this is my table rows :

这一件可怕的事情!花了我几个小时!这是我的表格行:

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);

Every time when I update the table , I will update the CURRENT_TIME for sort. But I found that it is not work.The result is not sorted what I want. Finally, I found that, the column "current_time" is the default row of sqlite. The solution is, rename the column "cur_time" instead of "current_time".

每次更新表时,我都会更新CURRENT_TIME进行排序。但我发现这不是工作。结果不是我想要的排序。最后,我发现,“current_time”列是sqlite的默认行。解决方案是,将列重命名为“cur_time”,而不是“current_time”。

#11


0  

SQLite ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");

SQLite ORDER BY子句用于根据一个或多个列按升序或降序对数据进行排序。光标c = scoreDb。查询(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);