2015年8月28日金曜日

Android OrmLiteの導入

  • 公開日:2015年08月28日

記事概要


AndroidでOrmLiteを利用した実装方法を記載した記事です。(検証した結果OrmLiteの導入は見送りました)

環境


  • Android Studio 1.3.0
  • OS X Yosemite
  • android sdk 23(Android 6.0 Marshmallow(マシュマロ))
  • OrmLite

はじめに


最近ではAndroidでも色々なORM(データベースとオブジェクト指向プログラミング言語の間の非互換なデータを変換するプログラミング技法)が用意されています。
私はこれまで自作のDB操作クラスを利用してたのですが、今回はOrmLiteを調査したので、その方法をまとめました。

gradleの設定


まずはOrmLiteを利用できるようにgradleの設定を行ないます。
android sdkは23.0(Android 6.0 Marshmallow(マシュマロ))を利用します。


apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
    }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.j256.ormlite:ormlite-android:4.48'
}

compile 'com.j256.ormlite:ormlite-android:4.48'でOrmLiteを利用できるように設定しています。

DatabaseHelperの実装


続いてDatabaseHelperを実装します。DatabaseHelperはOrmLiteSqliteOpenHelperを継承したクラスにします。
Databaseの作成、更新、処理時のクローズ処理等の共通処理の役割を担うようにします。
パッケージを分けている場合は、FragmentやActivityのui系とは別のutilに置くのが一般的でしょう。


public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    // name of the database file for your application -- change to something appropriate for your app
    private static final String DATABASE_NAME = "sample.db";
    // any time you make changes to your database objects, you may have to increase the database version
    private static final int DATABASE_VERSION = 1;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
    }

    /**
     * This is called when the database is first created. Usually you should call createTable statements here to create
     * the tables that will store your data.
     */
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
        try {
            Log.i(DatabaseHelper.class.getName(), "onCreate");
            TableUtils.createTable(connectionSource, LocationItem.class);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }

        Log.i(DatabaseHelper.class.getName(), "created new entries in onCreate: ");
    }

    /**
     * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
     * the various data to match the new version number.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            Log.i(DatabaseHelper.class.getName(), "onUpgrade");
            TableUtils.dropTable(connectionSource, LocationItem.class, true);
            // after we drop the old databases, we create the new ones
            onCreate(db, connectionSource);
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Close the database connections and clear any cached DAOs.
     */
    @Override
    public void close() {
        super.close();
    }
}

続いてormlite_config.txtを用意します。ormlite_config.txtには作成するテーブルの情報を記載します。
取得した現在情報を格納するLocationテーブルを作成します。
配置場所はres/rawの配下です。


#
# generated on 2015/08/27
#
# --table-start--
dataClass=mtchannel.com.mtscouter.model.Location
tableName=location
# --table-fields-start--
# --field-start--
fieldName=id
generatedId=true
# --field-end--
# --field-start--
fieldName=latitude
# --field-end--
# --field-start--
fieldName=longitude
# --field-end--
# --field-start--
fieldName=altitude
# --field-end--
# --field-start--
fieldName=created_at
# --field-end--
# --field-start--
fieldName=updated_at
# --field-end--
# --table-fields-end--
# --table-end--

最後にテーブルにアクセスするクラスを作成します。


@DatabaseTable(tableName = "location" )
public class Location {

    // id is generated by the database and set on the object automagically
    @DatabaseField(generatedId = true)
    int id;
    String latitude;
    @DatabaseField
    String longitude;
    @DatabaseField
    String altitude;
    @DatabaseField
    Date created_at;
    @DatabaseField
    Date updated_at;

    Location() {
        // needed by ormlite
    }

}

これで準備は完了です。あとはActivityからOpenHelperManager.getHelperメソッドを利用すればsqliteを利用できます。
しかし、さらに調査をすすめたところ、sqlの実行速度の問題やリフレクションにコストがかかる等の問題点があるのがわかりました。
それらを考慮した結果、自作のDB操作クラスをリファクタリングして使用することにしました。

まとめ


Androidの実装にORMを使うと柔軟性が著しく落ちる気がします。
ContentProviderかSQLiteOpenHelperを使って実装するのが、結局はBEST PRACTICEというのが、android1.6の時代から実装してきた結論になります。

以上

Androidアプリ開発にオススメの本


開発にあると便利なオススメ製品


参考サイト

この記事がお役にたちましたらシェアをお願いします

このエントリーをはてなブックマークに追加

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...