コンテンツ プロバイダーを使用する場合、DBHelper クラスを使用してデータベースの作成を管理していると思います。以下は、android notes サンプル プロジェクトのコードです。
これは、DBHelper コンストラクターが、データベースが以前に作成されているかどうかを判断するのに十分なほどインテリジェントであることを示しています。createDatabase メソッドでは、json ファイルと言うように、データベースに事前入力するメソッドを呼び出します。
問題は、データベースが初期化されていないことをアクティビティに伝えることが実際にはできないことです。
データベースにデータを入力したという事実を格納するために SharedPreferences を使用することが 1 つの考えかもしれません。次に、起動時のアクティビティで sharedPreference を確認し、コンテンツ プロバイダーを呼び出してデータベースにデータを入力し、このタスクを既に実行したことを共有設定に保存します。
たとえば、Android設定メニューからデータを消去した場合、sharedPreferencesがデータベースと同じ状態を維持するかどうかわからないことに注意してください。それを確認する必要があります。
http://code.google.com/p/android-notes/source/browse/trunk/src/com/bitsetters/android/notes/DBHelper.java?r=10
public class DBHelper {
private static final String DATABASE_NAME = "notes";
private static final String TABLE_DBVERSION = "dbversion";
private static final String TABLE_NOTES = "notes";
private static final int DATABASE_VERSION = 1;
private static String TAG = "DBHelper";
Context myCtx;
private static final String DBVERSION_CREATE =
"create table " + TABLE_DBVERSION + " ("
+ "version integer not null);";
private static final String NOTES_CREATE =
"create table " + TABLE_NOTES + " ("
+ "id integer primary key autoincrement, "
+ "note text, "
+ "lastedit text);";
private static final String NOTES_DROP =
"drop table " + TABLE_NOTES + ";";
private SQLiteDatabase db;
/**
*
* @param ctx
*/
public DBHelper(Context ctx) {
myCtx = ctx;
try {
db = myCtx.openOrCreateDatabase(DATABASE_NAME, 0,null);
// Check for the existence of the DBVERSION table
// If it doesn't exist than create the overall data,
// otherwise double check the version
Cursor c =
db.query("sqlite_master", new String[] { "name" },
"type='table' and name='"+TABLE_DBVERSION+"'", null, null, null, null);
int numRows = c.getCount();
if (numRows < 1) {
CreateDatabase(db);
} else {
int version=0;
Cursor vc = db.query(true, TABLE_DBVERSION, new String[] {"version"},
null, null, null, null, null,null);
if(vc.getCount() > 0) {
vc.moveToFirst();
version=vc.getInt(0);
}
vc.close();
if (version!=DATABASE_VERSION) {
Log.e(TAG,"database version mismatch");
}
}
c.close();
} catch (SQLException e) {
Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
} finally {
db.close();
}
}
private void CreateDatabase(SQLiteDatabase db)
{
try {
db.execSQL(DBVERSION_CREATE);
ContentValues args = new ContentValues();
args.put("version", DATABASE_VERSION);
db.insert(TABLE_DBVERSION, null, args);
db.execSQL(NOTES_CREATE);
// Populate with data
populateDataBaseFromFile();// There are probably better ways to do this.
setSharedPreferenceYouPopulatedDB();
} catch (SQLException e) {
Log.d(TAG,"SQLite exception: " + e.getLocalizedMessage());
}
}
個人的には、本当に必要でない限り、スプラッシュ スクリーンは気にしません。
別の考えは次のとおりです。
- テーブルが存在するかどうかを判断するメソッドを db ヘルパーに記述します。そうでない場合は false を返します。
- 起動アクティビティで、DBHelper テスト メソッドを呼び出す要求で ContentProvider を呼び出します。
- false の場合、スプラッシュ スクリーンを表示し、コンテンツ プロバイダーを呼び出して DB に入力します。
- true の場合は、通常どおり続行します。