0

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.

user
  • 86,916
  • 18
  • 197
  • 190
regrecall
  • 521
  • 1
  • 6
  • 20
  • 1
    Try to remove the `finally{ db.close(); }` – user Mar 02 '12 at 08:19
  • Thanks a lot. It works successfully, but in the another project i always closed after wirte , it works. why can't close the database in content provider? – regrecall Mar 02 '12 at 08:55
  • I don't know why. Some time ago I was trying to solve some database exceptions and I saw your type of error and kept in mind one of the answers, what I said above. I've made a little test in one of my `ContentProvider` with a `try-finally` and a simple `insert` and it works flawless. – user Mar 02 '12 at 10:14
  • there should be a previous error when you try to open the database – njzk2 Mar 02 '12 at 11:16
  • From the Android example NotePad, the ContentProvider doesn't close the database in it. So I think Content Provider can't close in it, the database in it managed by the Android system. – regrecall Mar 03 '12 at 03:46

1 Answers1

0

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.

ol_v_er
  • 27,094
  • 6
  • 48
  • 61