AndroidのSQLiteでORDER BYを使う方法|データを昇順ソートして表示するサンプル
AndroidにおけるSQLiteとは
具体例に入る前に、AndroidにおけるSQLiteデータベースについて簡単に確認しておきましょう。SQLiteはオープンソースのSQLデータベースで、デバイス上のテキストファイルにデータを保存します。Androidには標準でSQLiteデータベースの実装が組み込まれており、リレーショナルデータベースの機能をすべてサポートしています。また、JDBCやODBCのような接続確立の手続きが不要なため、非常に手軽に利用できる点も大きな特徴です。
本記事では、AndroidのSQLiteでORDER BY句を使ってデータを並べ替える方法を、実際のコード例とともに解説します。
実装手順
ステップ1:新しいプロジェクトを作成する
Android Studioを開き、「File」→「New Project」を選択して、必要な情報を入力し、新しいプロジェクトを作成します。
ステップ2:レイアウトファイル(activity_main.xml)を編集する
res/layout/activity_main.xml に以下のコードを追加します。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter Name" android:layout_height="wrap_content" /> <EditText android:id="@+id/salary" android:layout_width="match_parent" android:inputType="numberDecimal" android:hint="Enter Salary" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"><Button android:id="@+id/save" android:text="Save" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/refresh" android:text="Refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/udate" android:text="Update" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout>
このコードでは、名前と給与を入力する2つのEditTextを用意しています。「Save」ボタンをタップすると入力内容がSQLiteデータベースに保存され、値を挿入した後に「Refresh」ボタンをタップすると、ORDER BYによる並べ替え済みの結果からListViewが更新されます。さらに「Update」ボタンで既存データの更新も行えます。
ステップ3:MainActivity.java を編集する
src/MainActivity.java に以下のコードを追加します。
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button save, refresh;
EditText name, salary;
private ListView listView;
@Override
protected void onCreate(Bundle readdInstanceState) {
super.onCreate(readdInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = helper.getAllCotacts();
name = findViewById(R.id.name);
salary = findViewById(R.id.salary);
listView = findViewById(R.id.listView);
final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);
listView.setAdapter(arrayAdapter);
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll(helper.getAllCotacts());
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.insert(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
}
}ステップ4:DatabaseHelper.java を作成する
src/DatabaseHelper.java に以下のコードを追加します。ここが本記事のポイントとなる部分です。getAllCotacts()メソッド内のSQLクエリで「ORDER BY name」を指定することで、取得したレコードが名前の昇順(ASC)で並べ替えられます。
package com.example.andy.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
import java.util.ArrayList;
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "salaryDatabase5";
public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(
"create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary text,datetime default current_timestamp )"
);
} catch (SQLiteException e) {
try {
throw new IOException(e);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
onCreate(db);
}
public boolean insert(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", s);
contentValues.put("salary", s1);
db.replace(CONTACTS_TABLE_NAME, null, contentValues);
return true;
}
public ArrayList getAllCotacts() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> array_list = new ArrayList<String>();
Cursor res = db.rawQuery( "select * from "+CONTACTS_TABLE_NAME+" ORDER BY name", null );
res.moveToFirst();
while(res.isAfterLast() == false) {
array_list.add(res.getString(res.getColumnIndex("name")));
res.moveToNext();
}
return array_list;
}
public boolean update(String s, String s1) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("UPDATE "+CONTACTS_TABLE_NAME+" SET name = "+"'"+s+"', "+ "salary = "+"'"+s1+"'");
return true;
}
public boolean delete() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE from "+CONTACTS_TABLE_NAME);
return true;
}
}アプリを実行して動作を確認する
それでは、アプリケーションを実行してみましょう。実機のAndroidスマートフォンをPCに接続しているものとして説明します。Android Studioからアプリを実行するには、プロジェクト内のアクティビティファイルのいずれかを開き、ツールバーの「Run」アイコンをクリックします。表示される選択肢から自分のモバイルデバイスを選択すると、接続した端末にデフォルト画面が表示されます。

上記の画面では、いくつかの値を入力して保存しています。すべてのレコードを保存した後、「Refresh」ボタンをタップすると、下図のように名前が昇順(ASC)に並べ替えられた一覧が表示されます。

まとめ
このように、SQLiteのrawQueryでSELECT文に「ORDER BY カラム名」を付けるだけで、Androidアプリ内のデータベースから取得したレコードを簡単にソートできます。降順にしたい場合は「DESC」を指定するだけで対応可能です。データの一覧表示を扱うアプリでは頻出のテクニックなので、ぜひ覚えておきましょう。
-
Android SQLiteでunlikely()関数を使用する方法をわかりやすく解説
AndroidにおけるSQLiteデータベースとは 実装例に入る前に、まずAndroidにおけるSQLiteデータベースの基本を押さえておきましょう。SQLiteはオープンソースのSQLデータベースエンジンで、デバイス上のテキストファイルとしてデータを保存するのが特徴です。 Androidには標準でSQLiteデータベースの実装が組み込まれており、リレーショナルデータベースが持つすべての機能をサポートしています。また、JDBCやODBCのような接続設定を行う必要がなく、そのまま手軽にデータベースへアクセスできる点も大きなメリットです。 本記事では、Android SQLiteでunlikely
-
AndroidのSQLiteでunicode()関数を使う方法を徹底解説!実装サンプル付き
AndroidのSQLiteデータベースとは?具体例に入る前に、まずAndroidにおけるSQLiteデータベースについて簡単に確認しておきましょう。SQLiteはオープンソースのSQLデータベースで、デバイス上のテキストファイルにデータを保存します。AndroidにはSQLiteデータベースの実装が標準で組み込まれており、リレーショナルデータベースの機能をすべてサポートしています。また、このデータベースにアクセスする際は、JDBCやODBCなどのような接続確立の手順が一切不要という点も大きな特徴です。本記事では、AndroidのSQLiteでunicode()関数を使用する方法を、実際のサン