プログラマーのメモ書き

伊勢在住のプログラマーが気になることを気ままにメモったブログです

【Android】 SQLite と CursorLoader の使い方(1/3): SQLite の設定

一番遅い終電検索のバージョンアップを検討していると、新しいSDK の作法では、SQLite を使う場合CursorLoader というものを使うのが流儀のようです。

なので、自分なりにSQLiteを使う場合の設定、Content Provider / Resolver の使い方、CursorLoader の使い方を調べてみたので、まとめておきます。試した際のSDK、ADTは共に、20です。

 

SQLiteの設定

まず最初にSQLiteを設定します。愚鈍人:SQLiteでデータベース などを参考に、SQLiteOpenHelperの派生クラスを定義します。

package com.mori_soft.android.sqlitesample;

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

public class SampleTblOpenHelper extends SQLiteOpenHelper {

    private static final int DB_VERSION = 1;
    
    public SampleTblOpenHelper(Context context) {
        super(context, "sample_db", null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table person_table("+
                "   name text not null,"+
                "   age text"+
                ");"
                );
                
        // table row insert
        db.execSQL("insert into person_table(name,age) values ('本田 圭佑', 24);");
        db.execSQL("insert into person_table(name,age) values ('遠藤 保仁', 30);");
        db.execSQL("insert into person_table(name,age) values ('松井 大輔', 29);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

}

次に、ActivityはListViewを簡単に使うためにListActivityを継承して、下記のようにしました。

package com.mori_soft.android.sqlitesample;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;


public class MainActivity extends ListActivity {

    /* (non-Javadoc)
    * @see android.app.Activity#onCreate(android.os.Bundle)
    */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        SampleTblOpenHelper helper = new SampleTblOpenHelper(this);
        SQLiteDatabase db = helper.getReadableDatabase();
        
        Cursor c = db.rawQuery("select rowid as _id, name, age from person_table",null);
        this.startManagingCursor(c);
        
        ListAdapter adapter = new SimpleCursorAdapter(
                this,
                android.R.layout.two_line_list_item,
                c,
                new String[] {"name", "age"},
                new int[] {android.R.id.text1, android.R.id.text2});

        // Bind to our new adapter.
        setListAdapter(adapter);
    }

}

なお、ここで使っているstartManagingCursor や SimpleCursorAdapterのコンストラクタ は既にdeprecated になっているので、実際のアプリ開発では使わないようにしたほうが無難です。このやり方ではUIスレッドでDBへの問い合わせを行うことやCursorのrequeryが発生することなどから、CursorLoaderを使うのが推奨ですが、サンプルなのでとりあえず使ってます。

レイアウトファイルはListViewを一つだけ持つものとしています。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

マニフェストは次の通りです。minSdkVersion = 4 , targetSdkVersion = 15 としました。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mori_soft.android.sqlitesample"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15" />

    <application android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">
    
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
    </application>

</manifest>

実行した結果は、次のようになります。

これで、SQLiteを使う準備ができました。