4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLiteで昇順・降順にソートする方法

Last updated at Posted at 2019-05-06

#概要
データベースから値を取得するとき、昇順・降順にソートしてから取得ができる
※前提条件として、SQLiteOpenHelperを使用してデータベースに値が入っていること

#使い方

number title
15 ABCD
67 EFGH
22 IJKL
12 MNOP

例えば上記のようにデータベース(DB)に値があったとする

        if(helper == null){
            helper = new TestOpenHelper(getActivity().getApplicationContext());
        }

        if(db == null){
            db = helper.getReadableDatabase();
        }
        Cursor cursor = db.query(
                "testdb",
                new String[] { "number","title" },
                null, //selection
                null, //selectionArgs
                null, //groupBy
                null, //having
                null, //orderBy
        );

登録順にDBを取得するだけならこの方法で良い。

##order Byに指定する(ソート)

        if(helper == null){
            helper = new TestOpenHelper(getActivity().getApplicationContext());
        }

        if(db == null){
            db = helper.getReadableDatabase();
        }

        String order_by = "number ASC"; //ソートしたい値,昇順(ASC)か降順(DESC)か

        Cursor cursor = db.query(
                "testdb",
                new String[] { "number","title" },
                null, //selection
                null, //selectionArgs
                null, //groupBy
                null, //having
                order_by
        );

Cursorに値を代入する時にorder Byに指定する
→昇順はASC、降順はDESCを指定するだけ!

#その後(おまけ)

        //データリストを回す
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
       //ここに任意の処理を書く
            cursor.moveToNext();
        }
        cursor.close();

よく使う、ソート後のデータを取得する方法をメモ。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?