这就是我所做的,我创建了一个名为Database
is 的类,static
并让所有查询和所有数据库访问都通过它。如果我需要任何东西,我static
会在该类中创建一个函数,该函数Database
执行我需要的任何特定查询并返回一个Cursor
然后我在代码中处理的函数。这样,如果我需要更改任何查询,我只需要更改一个位置,而不是在我的代码中跑来跑去尝试查找所有实例。
当我Database
调用. 当然,所有调用都来自一个或第二个线程。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) {
}
}
对于从 Activity 访问:
Database.initiate(getBaseContext());
Cursor c = Database.selectNames();
从片段:
Database.initiate(getActivity());
Cursor c = Database.selectNames();