mercredi 30 mars 2016

Using Singleton SQLiteHelper in Service

I have a service that store data in SQLite. I want that service to keep running when the application is closed. (Swipe out) But I have an exception when my application is destroyed because the DatabaseHelper is also destroyed... How can I keep it alive even after my application is closed?

My database singleton class:

public class DbManager {
    private static DbManager instance;
    private CipherDbHelper dbHelper;

    private DbManager() {

    }

    private DbManager(Context context, String password) {
        SQLiteDatabase.loadLibs(context);
        dbHelper = new CipherDbHelper(context, password);
    }

    public static void init(Context context, String password) {
        instance = new DbManager(context, password);
    }

    public static DbManager getInstance() {
        if (instance == null) {
            throw new IllegalArgumentException("you should call DBManager.init(context) first");
        }
        return instance;
    }

    //Closing
    public void closeDatabase() {
        dbHelper.close();
        dbHelper = null;
        instance = null;
    }

    public <D extends Dao<T, String>, T> D getDAO(Class<T> clz) throws SQLException {
        return dbHelper.getDao(clz);
    }


}

I get the exception: You should call DBManager.init(context) first

Aucun commentaire:

Enregistrer un commentaire