Android 앱의 경우 SQLITE 데이터베이스를 내림차순으로 정렬하려면 어떻게해야합니까?
내 데이터를 내림차순으로 표시하는 가장 효율적인 방법은 무엇입니까?
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
}
쿼리에는 사용중인 구문이라는 두 가지 구문이 있습니다. 마지막 열은 orderBy를 나타냅니다. orderBy + "ASC"(또는) orderBy + "DESC"를 수행 할 열을 지정하면됩니다.
Cursor c = scoreDb.query(DATABASE_TABLE, rank, null, null, null, null, yourColumn+" DESC");
방법 에 대한 자세한 내용은 이 문서를 참조하십시오 query()
.
Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");
이 시도
return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
" ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
, new String[] {});
문서 에 따르면 :
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);
당신 BY ORDER PARAM 수단 :
SQL ORDER BY 절로 형식화 된 행을 정렬하는 방법 (ORDER BY 자체 제외) null을 전달하면 정렬되지 않은 기본 정렬 순서가 사용됩니다.
따라서 쿼리는 다음과 같습니다.
Cursor cursor = db.query(TABLE_NAME, null, null,
null, null, null, KEY_ITEM + " DESC", null);
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~
Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});
this works for me!!!
you can do it with this
Cursor cursor = database.query(
TABLE_NAME,
YOUR_COLUMNS, null, null, null, null, COLUMN_INTEREST+" DESC");
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");
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
TABLE_NAME,
rank,
null,
null,
null,
null,
COLUMN + " DESC",
null);
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
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
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) {
}
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".
'program tip' 카테고리의 다른 글
비 차단 IO 대 비동기 IO 및 Java 구현 (0) | 2020.11.30 |
---|---|
Java MessageFormat-작은 따옴표 사이에 값을 삽입하려면 어떻게해야합니까? (0) | 2020.11.30 |
Linux의 JAVA_HOME 디렉토리 (0) | 2020.11.29 |
루비에서 임의의 10 자리 숫자를 생성하려면 어떻게해야합니까? (0) | 2020.11.29 |
Twitter 애플리케이션 용 Android Intent (0) | 2020.11.29 |