Android SQLiteでレコードのIDを取得して表示する方法
本記事では、Androidに標準搭載されているSQLiteデータベースに保存されたレコードのID(主キー)を取得し、画面に表示する方法を、実際のコード例とともに詳しく解説します。
AndroidにおけるSQLiteとは
SQLiteはオープンソースのSQLデータベースエンジンで、データをデバイス上のテキストファイルとして保存します。AndroidにはSQLiteの実装が最初から組み込まれており、リレーショナルデータベースの基本的な機能をすべて利用できます。さらに、JDBCやODBCのような接続確立の手順が一切不要で、すぐに使い始められるのが大きな魅力です。
このサンプルでは、名前と給与を入力してSQLiteに保存するシンプルなアプリを作成し、保存された各レコードの「id」を含む情報をListViewに一覧表示します。
ステップ1:新規プロジェクトの作成
Android Studioで新しいプロジェクトを作成します。メニューから「File → New Project」を選択し、必要事項を入力してプロジェクトを作成しましょう。
ステップ2:レイアウトの定義(res/layout/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" />
<Button
android:id = "@+id/Delete"
android:text = "DeleteALL"
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>
このレイアウトでは、名前と給与を入力するためのEditTextを2つ配置しています。「Save」ボタンをタップすると入力内容がSQLiteデータベースに保存され、「Refresh」ボタンでカーソルから取得した最新データをListViewに再読み込みできます。また、「Update」ボタンでデータの更新、「DeleteALL」ボタンで全レコードの一括削除も可能です。
ステップ3:アクティビティの実装(src/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 savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = helper.getAllContacts();
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.Delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (helper.delete()) {
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Deleted", Toast.LENGTH_LONG).show();
}
}
});
findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.update(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Updated", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll(helper.getAllContacts());
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:データベースヘルパーの実装(src/DatabaseHelper.java)
以下のコードを src/DatabaseHelper.java に追加します。ここでのポイントは getAllContacts() メソッド内のSQL文です。「id || ' : ' || name || ' : ' || salary || ' : ' || datetime」のように文字列を連結することで、レコードのIDを名前・給与・日時と一緒にひとつの文字列として取得し、一覧に表示できるようにしています。
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 getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> array_list = new ArrayList<String>();
Cursor res = db.rawQuery( "select (id ||' : '||name || ' : ' || salary || ' : '|| datetime) AS fullname from "+CONTACTS_TABLE_NAME, null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex("fullname")));
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アイコンをクリックし、実行デバイスとして自分のモバイル端末を選択します。端末には次のような初期画面が表示されます。

上記の実行結果のように、各レコードは「id : 名前 : 給与 : 日時」の形式で表示され、SQLiteに保存されたレコードのIDを一目で確認できます。テーブル作成時に「id INTEGER PRIMARY KEY」と定義しているため、各レコードには自動的に一意のIDが採番されます。
-
Android SQLiteでMAX()関数を使う方法を徹底解説!実装サンプルコード付き
はじめに:AndroidにおけるSQLiteデータベースとは 具体的な例に入る前に、AndroidにおけるSQLiteデータベースについて簡単に確認しておきましょう。SQLiteは、デバイス上のテキストファイルにデータを保存するオープンソースのSQLデータベースです。Androidには標準でSQLiteデータベースの実装が組み込まれており、リレーショナルデータベースの機能をすべてサポートしています。 また、このデータベースにアクセスする際、JDBCやODBCのような接続設定は一切不要という点も大きな特徴です。 本記事では、Android SQLiteでMAX()関数を使用して最大値(最高給与)
-
AndroidのSQLiteでSUM()関数を使って合計値を取得する方法【サンプルコード付き】
SQLiteデータベースとは具体的な実装例に入る前に、AndroidにおけるSQLiteデータベースの基礎知識をおさらいしておきましょう。SQLiteはオープンソースのSQLデータベースエンジンで、デバイス内のテキストファイル形式でデータを保存します。Androidには標準でSQLiteの実装が組み込まれており、追加のライブラリなしですぐに利用できます。SQLiteはリレーショナルデータベースの主要な機能を一通りサポートしており、JDBCやODBCのような接続ドライバーを用意する必要がない点も大きな特徴です。アプリ内から直接アクセスできる手軽さが、Android開発で広く使われる理由です。本記