如何根据id对listview进行排序

时间:2014-03-07 21:22:15

标签: android sqlite sorting

我有以下类完美运行,但我希望显示按数据ID排序的结果;

public class TimeListDatabaseHelper {

    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_NAME = "timetracker.db";
    private static final String TABLE_NAME = "timerecords";
    private static final String TIMETRACKER_COLUMN_ID = "_id";
    private static final String TIMETRACKER_COLUMN_TIME = "time";
    private static final String TIMETRACKER_COLUMN_NOTES = "notes";

    private TimeTrackerOpenHelper openHelper;
    private SQLiteDatabase database;

    public TimeListDatabaseHelper(Context context) {
            openHelper = new TimeTrackerOpenHelper(context);
            database = openHelper.getWritableDatabase();
    }

    public void saveRecord(String time, String notes) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(TIMETRACKER_COLUMN_TIME, time);
            contentValues.put(TIMETRACKER_COLUMN_NOTES, notes);
            database.insert(TABLE_NAME, null, contentValues);
    }

    public Cursor getAllTimeRecords() {


            return database.rawQuery(
                            "SELECT * FROM " + TABLE_NAME,
                            null);
    }

    private class TimeTrackerOpenHelper extends SQLiteOpenHelper {

            public TimeTrackerOpenHelper(Context context) {
                    super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            @Override
            public void onCreate(SQLiteDatabase database) {
                    database.execSQL("CREATE TABLE " + TABLE_NAME + "("
                                    + TIMETRACKER_COLUMN_ID + " INTEGER PRIMARY KEY, "
                                    + TIMETRACKER_COLUMN_TIME + " text, "
                                    + TIMETRACKER_COLUMN_NOTES + " TEXT)");

            }

            @Override
            public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
                    database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME + "");
                    onCreate(database);

            }

    }

}

这很好但是按此顺序显示数据;

ID
1
2
3
4

但是我想要它;

ID
4
3
2
1

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

在你的方法中,getAllTimeRecords只需添加你想要的命令sql命令

   public Cursor getAllTimeRecords(boolean desc) {
        return database.rawQuery("SELECT * FROM " +TABLE_NAME+ " ORDER BY "+TIMETRACKER_COLUMN_ID +(desc?" DESC ":""),null);
   }