Robertas Setkus
Robertas Setkus

Reputation: 3161

Can't get SQLite writable database

I'm trying to implement android SQLite usage design pattern that ensures one opened SQLiteDatabase instance per application.

public class BaseDataSource {

    private static final CustomSQLiteHelper dbHelper = CustomSQLiteHelper.getInstance();

    protected static SQLiteDatabase database;

    static {
        //HERE RISES EXCEPTION
        BaseDataSource.database = BaseDataSource.dbHelper.getWritableDatabase();
    }



    private void close() {      
        if(null != BaseDataSource.database && BaseDataSource.database.isOpen()) {
            BaseDataSource.database.close();

            if(null != BaseDataSource.dbHelper) {
                BaseDataSource.dbHelper.close();                
            }
        }
    }

    protected BaseDataSource() {}


    protected void finalize () throws Throwable {
        close();
        super.finalize();       
    }
} 

But while my applications starts I get this kind exception:

Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.xxx/databases/xxx.db

How SQLiteDatabse database can be opened and closed before class was created?

UPDATED

I found my own bug. It was in CustomSQLiteHelper class. In onCreate method I closed database. I tried every soliution that I found in internet and due to that I made a bug.

Upvotes: 0

Views: 1645

Answers (3)

Sunil Kumar
Sunil Kumar

Reputation: 7092

if you going to event any thing then first need to open as write database. So for that use this method and call like this

openAsWrite();

    public void openAsWrite() throws SQLException {
            db = DBHelper.getWritableDatabase();
        }

        // ---closes the database---
        public void close() throws SQLException {
            DBHelper.close();
        }

Upvotes: 1

R9J
R9J

Reputation: 6715

Using database object as static makes your class behave like this.

  • Creates database instance when the class is loaded.
  • closes the database connection when finalize method is called.
  • your class will not going to acquire database connection anymore, and it will have the database instance which is closed already.
  • eventually when try to access the instance which is closed, it pops the error to you

I think you should use a different approach will be better.

Upvotes: 0

Shrikant Ballal
Shrikant Ballal

Reputation: 7087

Use following pattern when getting a database object:

try {
    if (sDatabase != null) {
        if (!sDatabase.isOpen()) {
            sDatabase = sContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
        }
    } else {
        // open database here
        sDatabase = sContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
    }
    Log.d(TAG, "Database successfully opened.");
} catch (SQLException e) {
    Log.e(TAG, "" + e);
}

Upvotes: 0

Related Questions