AndroidでSQLiteを利用する - Android

Andoroid端末に組み込まれているSQLiteを利用して、シンプルなデータベースアプリケーションを作成します。
補足
この記事ではSQLiteのデータベースファイルはファイルに保存されません。アプリケーションを終了するとデータベースに蓄積したレコードはなくなります。データベースファイルをファイルに保存するコードについてはこちらの記事を参照してください。

実装例: 2013年3月版

プロジェクトの設定

Androidアプリケーションプロジェクトを新規作成します。
  • Project name: SimpleSqlite
  • Build Target: Android 2.3
  • Application name: SimpleSqlite
  • Package name: com.iPentec.SimpleSqlite
  • Activity: MainActivity

UI

プロジェクトの作成後 /res/layout/activity_main.xml を開きデザイナ画面でUIを作成します。
今回はTextViewを一つ追加します。

コード

下記のコードを記述します。
MainActivity.java
package com.iPentec.simplesqlite;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MyDBHelper helper = new MyDBHelper(this);
    SQLiteDatabase db = helper.getReadableDatabase();

    // データ挿入
    db.execSQL("insert into products(name,price) values ('Pig', 250);");
    db.execSQL("insert into products(name,price) values ('Penguin', 120);");
    db.execSQL("insert into products(name,price) values ('Camel', 520);");
    db.execSQL("insert into products(name,price) values ('Hawk', 60);");

    // データ取り出し
    String text = "";
    Cursor c = db.query("products", new String[] { "name", "price" }, null,
        null, null, null, null);
    boolean isEof = c.moveToFirst();
    while (isEof) {
      text += String.format("%s : %d円\r\n", c.getString(0), c.getInt(1));
      isEof = c.moveToNext();
    }

    TextView textView1 = (TextView) findViewById(R.id.textView1);
    textView1.setText(text);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

}

解説

アプリケーション開始時にMyDBHelperクラスのインスタンスを作成します。インスタンスのgetReadableDatabase()メソッドを呼び出しデータベースオブジェクトを取得します。データベースオブジェクト取得後は、データベースオブジェクトのexecSQL()メソッドを呼び出しSQL文を実行しデータの挿入をします。
データの取り出しは、データベースオブジェクトのqueryメソッドを呼び出します。queryメソッドを呼び出すと検索結果のカレントレコードを表すCursorが取得できますので、Cursorを動かして検索結果を取得します。
上記の例では検索結果をStringに整形して保存し、TextViewに表示します。
MyDBHelper.java
package com.iPentec.simplesqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class MyDBHelper extends SQLiteOpenHelper {
  public MyDBHelper(Context context) {
    super(context, null, null, 1);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    // table create
    db.execSQL("create table products(" + "   name text not null,"
        + "   price text" + ");");
  }
}

解説

Sqliteを用いる場合はSQLiteOpenHelper クラスを継承したDBHelperを作成します。

実行結果

プロジェクトを実行します。アプリケーションが起動し下図の画面が表示されます。SQLiteにデータが挿入され取り出せていることが確認できます。

実装例: 以前のバージョン

プロジェクトの設定

Androidアプリケーションプロジェクトを新規作成します。
  • Project name: SimpleSqlite
  • Build Target: Android 2.2
  • Application name: Simple SQLite App
  • Package name: iPentec.SimpleSqlite
  • Activity: SimpleSQLite

UI

プロジェクトが新規作成されたら、/res/layout ノード内のmain.xmlを開きます。デザイナが表示されますのでTextViewコントロールを画面に配置します。(下図参照)


コード

以下のコードを実装します。
SimpleSQLite.java
package iPentec.SimpleSqlite;

import android.app.Activity;
import android.os.Bundle;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.content.Context;
import android.view.View;
import android.widget.TextView;

public class SimpleSQLite extends Activity {
	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		MyDBHelper helper = new MyDBHelper(this);
		SQLiteDatabase db = helper.getReadableDatabase();

		Cursor c = db.query("products", new String[] { "name", "price" },
				null, null, null, null, null);
		
		boolean isEof = c.moveToFirst();
		TextView textView1 = (TextView)findViewById(R.id.textView1);
		String text="";
		while (isEof) {
			text += String.format("%s : %d円\r\n", c.getString(0), c.getInt(1));
			isEof = c.moveToNext();
			//layout.addView(tv);
		}
		textView1.setText(text);
		c.close();
		db.close();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
		
	public class MyDBHelper extends SQLiteOpenHelper {
		public MyDBHelper(Context context) {
			super(context, null, null, 1);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// table create
			db.execSQL(
				"create table products("+
				"	name text not null,"+
				"	price text"+
				");"
			);

			// table row insert
			db.execSQL("insert into products(name,price) values ('Cookie', 120);");
			db.execSQL("insert into products(name,price) values ('Candy', 85);");
			db.execSQL("insert into products(name,price) values ('Cake', 285);");
		}
	}
}

解説

AndroidアプリケーションからSQLiteを利用する場合、SQLiteOpenHelperクラスから派生したヘルパークラスを実装する必要があります。今回はMyDBHelperクラスとしました。

MyDBHelperクラスの解説

ヘルパークラスMyDBHelperクラスのonCreateメソッドをオーバーライドし、初期化時のコードを実装します。
以下のコードでテーブル作成のSQLを実行します。
 db.execSQL(
   "create table products("+
   "	name text not null,"+
   "	price text"+
   ");"
 );

以下のコードでInsert文のSQLを実行してレコードを挿入します。
 db.execSQL("insert into products(name,price) values ('Cookie', 120);");
 db.execSQL("insert into products(name,price) values ('Candy', 85);");
 db.execSQL("insert into products(name,price) values ('Cake', 285);");

SimpleSQLite クラスの解説

ヘルパークラスのインスタンスを作成します。
  MyDBHelper helper = new MyDBHelper(this);

ヘルパークラスのgetReadableDatabase()メソッドを呼び出し、データベースオブジェクトを取得します。
  SQLiteDatabase db = helper.getReadableDatabase();

検索結果を得るためのカーソルを準備します。queryメソッドの第一引数にテーブル名を、第二引数に検索で取得する列名を与えます。
  Cursor c = db.query("products", new String[] { "name", "price" }, null, null, null, null, null);

カーソルを先頭に移動させます。
  boolean isEof = c.moveToFirst();

TextViewコントロールを取得します。
  TextView textView1 = (TextView)findViewById(R.id.textView1);

カーソルから検索結果を読み取り、結果文字列を準備します。カーソルはmoveToNext()メソッドで次に進めます。
 String text="";
 while (isEof) {
   text += String.format("%s : %d円\r\n", c.getString(0), c.getInt(1));
   isEof = c.moveToNext();
 }

結果文字列をTextViewコントロールに表示します。
  textView1.setText(text);

カーソルとデータベースを閉じます。
 c.close();
 db.close();

コード(main.xml)

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>

実行結果

アプリケーションを実行すると下図の画面が表示されます。SQLiteデータベースに追加したレコードの内容が表示されることを確認できます。


著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-04
作成日: 2011-03-11
iPentec all rights reserverd.