カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

Androidでデータベースを利用する【SQLite】

この記事は最終更新日から1年以上経過しています。

データベースが簡単に利用できるSQLiteOpenHelperクラスを使用します。
プラットフォームは1.6で作成。

【HelloSqliteActivity.java】

package android.sample.sqlite;

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

public class HelloSqliteActivity extends Activity {

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

    MySqlite helper = new MySqlite(this);
    SQLiteDatabase db = helper.getReadableDatabase();
    Cursor c = db.query("TABLE_NAME",
      new String[] { "number", "latitude", "longitude" },
      null, null, null, null, null);
    startManagingCursor(c); //リソースの扱いをActivityに委ねます
    boolean isEof = c.moveToFirst();
    TextView textView1 = (TextView)findViewById(R.id.textView1);
    String text="";
    while (isEof) {
      text += String.format("物件番号 : %s\r\n緯度 : %.6f\r\n経度 : %.6f\r\n\r\n",
        c.getString(0), c.getDouble(1), c.getDouble(2));
      isEof = c.moveToNext();
    }

    textView1.setText(text);
    c.close();
    db.close();
    }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }
    
}


【MySqlite.java】

package android.sample.sqlite;

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

public class MySqlite extends SQLiteOpenHelper {

  public MySqlite(Context context) {
    super(context, null, null, 1);
    // 2番目の引数は、データベース名です。
    // nullにした場合はメモリ上に、データベース名を指定した場合はデータベースファイルが作成されます。
  }

  @Override
  public void onCreate(SQLiteDatabase db) {

    db.execSQL(
      "create table TABLE_NAME"
      + "( _id integer primary key autoincrement, number text not null, latitude double, longitude double );");

    db.beginTransaction();

    try {
      SQLiteStatement stmt =
        db.compileStatement(
          "insert into TABLE_NAME"
          + "( number, latitude, longitude )"
          + " values ( ?, ?, ? );"
            );
      stmt.bindString(1, "1000000");
      stmt.bindDouble(2, 34.1250);
      stmt.bindDouble(3, 135.12);
      stmt.executeInsert();

      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists TABLE_NAME;");
    onCreate(db);
  }

}

onCreateはまだデータベースがない場合の初期化に使用されます。
onUpgradeはデータベースのアップグレードが必要な時に呼ばれます。

また、データ挿入の際は以下のような方法も可能です。

  @Override
  public void onCreate(SQLiteDatabase db) {

    db.execSQL(
      "create table TABLE_NAME"
      + "( _id integer primary key autoincrement, number text not null, latitude double, longitude double );");

    ContentValues cv = new ContentValues(3);

    cv.put("number", "1000000");
    cv.put("latitude", 34.1250);
    cv.put("longitude", 135.12);
    db.insert(TABLE_NAME, null, cv);
  }

簡単にデータを挿入するには以下のように

    try {
      db.execSQL("insert into " + SerializeData.tblName
        + "( number, latitude, longitude )"
        + " values ( " + number + ", " + latitude + ", " + longitude + " );");
    } catch (SQLException e) {
      e.printStackTrace();
    }
この記事がお役に立ちましたらシェアお願いします
5,429 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です