how should I open and close my database properly

前端 未结 5 1749
挽巷
挽巷 2021-02-06 06:39

I have an app which stores some data in a SQLite DB.Also I\'m doing a lot of query an requery in my app.I have about 15 activities in it.And almoust all use the DB to query for

5条回答
  •  没有蜡笔的小新
    2021-02-06 07:28

    When you retrieve your dbAdapter from you MyApplication class, do it in a lazy fashion, creating it only when needed. In my implementation, I also open it at this time.

    public static DbAdapter getDbAdapter() {
        if (dbAdapter == null) {
            dbAdapter = new DbAdapter();
        }
        dbAdapter.open();
        return dbAdapter;
    }
    

    It is a good idea to use getReadableDatabase() or getWriteableDatabase() in the open method of your database adapter.

    Also, I think it works better to retrieve your adapter in onStart() and close it in onStop() of the activities where it is being used, rather than using onCreate() and onDestroy().

    @Override
    protected void onStop() {
        super.onStop();
        MyApp.closeDatabase();
    }
    

    And in the MyApp class...

    public static void closeDatabase() {
        dbAdapter.close();
    }
    

提交回复
热议问题