【问题标题】:Android insert the data SQLite error Caused by java.lang.IllegalStateException: database not openAndroid 插入数据 SQLite 错误 Caused by java.lang.IllegalStateException: database not open
【发布时间】:2012-11-15 22:24:55
【问题描述】:

当我从服务器获取数据时,我将数据插入到我自己的内容提供程序中,但它总是出错。这是日志

 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)

这是我在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();
 }

我在android源代码中发现错误信息,它会检查SQLiteDatabase.isOpen(),在getWritableDatabase函数中,它总是检查数据库是否打开?

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

所以我不知道导致这个错误的真正原因是为什么数据库没有打开。

【问题讨论】:

  • 尝试删除finally{ db.close(); }
  • 非常感谢。它可以成功运行,但是在另一个项目中我总是在 wirte 之后关闭,它可以正常工作。为什么不能在内容提供者中关闭数据库?
  • 我不知道为什么。前段时间我试图解决一些数据库异常,我看到了你的错误类型,并记住了我上面所说的答案之一。我用try-finally 和一个简单的insert 在我的ContentProvider 中做了一个小测试,它完美无瑕。
  • 尝试打开数据库时应该有之前的错误
  • 从 Android 示例记事本中,ContentProvider 不会关闭其中的数据库。所以我认为Content Provider不能在里面关闭,里面的数据库是由Android系统管理的。

标签: android sqlite android-contentprovider


【解决方案1】:

我遇到了完全相同的问题。

正如@Luksprog 在第一条评论中提到的,只需删除

db.close();

通常,在内容提供程序中,您永远不必显式关闭数据库。助手会为您完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多