通过desc的Android Sqlite命令无法正常工作

时间:2013-12-24 08:10:13

标签: android android-sqlite sqlite

我对使用Sqlite数据库编程的Android非常陌生。 我想通过desc我的游戏分数列来订购。游戏得分列类型是真实的,当我尝试通过gpoint和desc无法正常工作时。请给我一些建议。代码如下:

public List<Score> getAllScores() {
            List<Score> scoreList = new ArrayList<Score>();
            String selectQuery = "SELECT  * FROM " + TABLE_SCORES+" ORDER BY gpoint DESC";

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            if (cursor.moveToFirst()) {
                do {
                    Score score = new Score();
                    score.setID(Integer.parseInt(cursor.getString(0)));
                    score.setPoint(cursor.getFloat(1));
                    score.setLetter(cursor.getString(3));
                    score.setDate(cursor.getString(2));
                    scoreList.add(0, score);
                } while (cursor.moveToNext());
            }

            return scoreList;
        }

我的测试插入是:

            Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
        String formattedDate = df.format(c.getTime());

        Log.d("Insert: ", "Inserting .."); 
        db.addScoreToDB(new Score((float)9.4, "S",formattedDate));        
        db.addScoreToDB(new Score((float)7.5, "S",formattedDate));        
        db.addScoreToDB(new Score((float)6.6, "S",formattedDate));        
        db.addScoreToDB(new Score((float)8.8, "S",formattedDate));        
        db.addScoreToDB(new Score((float)9.7, "S",formattedDate));
        db.addScoreToDB(new Score((float)11.1, "S",formattedDate));
        db.addScoreToDB(new Score((float)2.1, "S",formattedDate));
        db.addScoreToDB(new Score((float)10.1, "S",formattedDate));

结果是:

12-24 15:52:24.065:D / Insert:(9901):插入.. 12-24 15:52:24.290:D /阅读:(9901):阅读所有联系人..
Id:8,得分:10.1,信:S
Id:6,得分:11.1,信:S
Id:7,得分:2.1,信:S
Id:3,得分:6.6,信:S
Id:2,得分:7.5,信:S
Id:4,得分:8.8,信:S
Id:1,得分:9.4,信:S
对:5,得分:9.7,信:S

我想要结果:2.1,6.6,7.5 ......等等

3 个答案:

答案 0 :(得分:6)

  

我想要结果:2.1,6.6,7.5 ......等等

这是一个升序,而不是下降。升序是默认值,但您也可以指定ORDER BY column ASC

Id: 8 ,Score: 10.1 ,Letter: S
Id: 6 ,Score: 11.1 ,Letter: S
Id: 7 ,Score: 2.1 ,Letter: S 
Id: 3 ,Score: 6.6 ,Letter: S 
Id: 2 ,Score: 7.5 ,Letter: S 
Id: 4 ,Score: 8.8 ,Letter: S 
Id: 1 ,Score: 9.4 ,Letter: S 
Id: 5 ,Score: 9.7 ,Letter: S

这是一个升序,但是按字母顺序(字母顺序)排序,而不是数字排序。如果您想要数字排序,请将gpoint列类型设置为REAL或将值转换为REAL

CREATE TABLE ... (... gpoint REAL ...)

SELECT ... ORDER BY CAST(gpoint AS REAL)

答案 1 :(得分:2)

请更改此查询:

String selectQuery = "SELECT  * FROM " + TABLE_SCORES+" ORDER BY gpoint DESC";

在REAL上转换gpoint。

String selectQuery = "SELECT  * FROM " + TABLE_SCORES+" ORDER BY cast(gpoint as REAL) DESC";

我希望这很有用。

答案 2 :(得分:0)

试试吧 返回mDb.query(DATABASE_TABLE,new String [] {KEY_ROWID,KEY_TITLE,         KEY_BODY,KEY_TIME,KEY_CATEGORY,KEY_ALARM},null,null,null,null,KEY_TIME +“DESC”);