これが私が行うことです。Database
which isというクラスを作成し、static
すべてのクエリとすべてのデータベースアクセスがそれを通過するようにします。何か必要な場合は、static
そのクラス内に関数を作成します。この関数は、必要な特定のクエリを実行し、コードで処理する をDatabase
返します。Cursor
このように、クエリを変更する必要がある場合、1 つの場所を変更するだけで済み、すべてのインスタンスを見つけようとしてコードを実行する必要がありません。
を呼び出すと、クラスはその内部にクラスDatabase
のインスタンスを作成します。もちろん、すべての呼び出しは1 つまたは 2 番目のスレッドからのものです。SQLiteHelper
Database.open(context)
Database
AsyncTask
繰り返しますが、私の個人的なデザインです。自由に好きなことをしたり、独自のデザインを考えたりしてください。
public final class Database {
private static SQLHelper sqlhelper = null;
private static SQLiteDatabase database = null;
private static Context context = null;
/** Prevents Instances */
private Database(){};
/**
* Initiates the Database for access
* @param context Application context
*/
public static void initiate(Context context){
if (sqlhelper == null)
sqlhelper = new SQLHelper(context);
if (Database.context == null)
Database.context = context;
}
/**
* Opens the database for reading
* @throws SQLException if the database cannot be opened for reading
*/
public static void openReadable() throws SQLException{
if (database == null)
database = sqlhelper.getReadableDatabase();
}
/**
* Opens the database for writing
* Defaults to Foreign Keys Constraint ON
* @throws SQLException if the database cannot be opened for writing
*/
public static void openWritable() throws SQLException{
if ((database == null)? true : database.isReadOnly()) {
openWritable(true);
}
}
/**
* Opens the database for writing
* @param foreignKeys State of Foreign Keys Constraint, true = ON, false = OFF
* @throws SQLException if the database cannot be opened for writing
*/
public static void openWritable(boolean foreignKeys) throws SQLException{
database = sqlhelper.getWritableDatabase();
if (foreignKeys) {
database.execSQL("PRAGMA foreign_keys = ON;");
} else {
database.execSQL("PRAGMA foreign_keys = OFF;");
}
}
/**
* Closes the database
*/
public static void close(){
if (database != null){
database.close();
database = null;
}
if (sqlhelper != null){
sqlhelper.close();
sqlhelper = null;
}
}
/* Add functions here */
public static Cursor selectNames(){
openReadable();
return database.rawQuery("SELECT * FROM names", null);
}
}
final class SQLHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "core.db";
//private final Context context;
SQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db){
// Create the tables
}
@Override
public void onOpen(SQLiteDatabase db){
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
アクティビティからのアクセスの場合:
Database.initiate(getBaseContext());
Cursor c = Database.selectNames();
そしてフラグメントから:
Database.initiate(getActivity());
Cursor c = Database.selectNames();