在后台线程中打开Sqlite数据库

时间:2016-04-20 00:11:19

标签: android database multithreading sqlite android-activity

我想更好地理解在Android中的后台线程上打开Sqlite数据库意味着什么。现在我通过我的类DatabaseHelper为我的数据库使用静态/单例模式,所以我只需要打开它一次,但我想用良好的做法打开它并理解为什么我不应该直接打开它从我的Activity直接(或在帮助者的构造函数中)。

我的课程:

public class DatabaseHelper extends SQLiteOpenHelper {
    private static volatile SQLiteDatabase mDatabase;
    private static DatabaseHelper mInstance = null;
    private static Context mContext;

    // ...

    public static synchronized DatabaseHelper getInstance(Context context) {
        /**
         * use the application context as suggested by CommonsWare.
         * this will ensure that you don't accidentally leak an Activity's
         * context (see this article for more information:
         * http://android-developers.blogspot.nl/2009/01/avoiding-memory-leaks.html)
         */
        if (mInstance == null) {
            mInstance = new DatabaseHelper(context.getApplicationContext());
        }
        return mInstance;
    }

    private DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DB_CREATE_SOME_TABLE); //some SQL expression
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
        db.execSQL(DB_ALTER);
    }

    public void open() throws SQLException {
        mDatabase = getWritableDatabase();
    }

    public void close() {
        mDatabase.close();
    }

    public boolean isOpen() {
        return mDatabase.isOpen();
    }

    //below this would be various CRUD functions operating on mDatabase
    // ...
    // ...
}

说你应该这样做是否正确:

   DatabaseHelper mDatabaseHelper = DatabaseHelper.getInstance(this);

   Thread thread = new Thread("OpenDbThread") {
      public void run(){
        mDatabaseHelper.open();
      }
   };


   thread.start();

Activity某个地方?

1 个答案:

答案 0 :(得分:0)

您所写的代码在后台线程上打开数据库是正确的。但是,在thread.isAlive()返回false(或mDatabase.isOpen()返回true)之前,您实际上不会打开数据库。或者,您可以让您的活动侦听来自您的线程的回调。