Android insert the data SQLite error Caused by java.lang.IllegalStateException: database not open

情到浓时终转凉″ 提交于 2019-12-25 08:20:01

问题


When I get the data from the server, I insert the data into the my own content provider, but it always error. This is the log

 Caused by: java.lang.IllegalStateException: database not open
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1585)
at com.weiboa.data.StatusProvider.insert(StatusProvider.java:107
    at android.content.ContentProvider$Transport.insert(ContentProvider.java:210)
    at android.content.ContentResolver.insert(ContentResolver.java:606)
    at com.weiboa.util.WeiboUserUtil.insertTweet(WeiboUserUtil.java:121)

and this is my insert code in my ContentProvider:

SQLiteDatabase db = dbHelper.getWritableDatabase();
try{
    long id = db.insertWithOnConflict(TABLE, null, values,SQLiteDatabase.CONFLICT_REPLACE);
    if(id == -1){
        throw new RuntimeException(String.format("%s : Failed to insert [%s] to [%s] for unknow reason,", TAG, values, uri));
    }else{
        return ContentUris.withAppendedId(uri, id);
    }
 }finally{
    db.close();
 }

And i find the error message in the android source code, it will check the SQLiteDatabase.isOpen(), and in the function getWritableDatabase, it always checked the database is open?

if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
        return mDatabase;  // The database is already open for business
    }

So I don't know the real reason to caused this error why the database is not opened.


回答1:


I had exactly the same problem.

As @Luksprog mentioned in the first comment just remove the

db.close();

In general, in a content provider, you never have to explicitly close the Database. The helper does it for you.



来源:https://stackoverflow.com/questions/9529995/android-insert-the-data-sqlite-error-caused-by-java-lang-illegalstateexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!