java.lang.IllegalStateException: attempt to re-open an already-closed object

最后,我还是通过单例模式和“短时间内不关闭SQLiteDatabase”解决了问题。

在自定义的DbHelper类(大部分人定义为DatabaseHelper)中:

public static synchronized DbHelper getInstance(Context context){
		if(dbInstance == null){
			dbInstance = new DbHelper(context.getApplicationContext());
		}
		return dbInstance;
	}

在自定义的DbOperations类中:

//构造函数
	public DbOperations(Context context){
		dbHelper = new DbHelper(context).getInstance(context);
	}

	//封装sqlite的打开方法
	public void open(Context context) throws SQLException{
		db = dbHelper.getInstance(context).getReadableDatabase();
	}

	//封装sqlite的关闭方法0
	public void close(Context context){
		dbHelper.getInstance(context).close();
	}

Android开发中,正确的管理你的SQliteDatabase,如果你有好的解决方法,可以留言,一起交流

以下是参考的solutions:

Correctly Managing your SQLite Database

One thing that I‘ve noticed other Android developers having trouble with is properly setting up their SQLiteDatabase. Often times, I come across questions on StackOverflow asking about error messages such as,

E/Database(234): Leak found E/Database(234): Caused by: java.lang.IllegalStateException: SQLiteDatabase created and never closed

As you have probably figured out, this exception is thrown when you have opened more SQLiteDatabase instances than you have closed. Managing the database can be complicated when first starting out with Android development, especially to those who are just
beginning to understand the Activity lifecycle. The easiest solution is to make your database instance a singleton instance across the entire application‘s lifecycle. This will ensure that no leaks occur, and will make your life a lot easier since it eliminates
the possibility of forgetting to close your database as you code.

Here are two examples that illustrates three possible approaches in managing your singleton database. These will ensure safe access to the database throughout the application.

Approach #1: Use a Singleton to Instantiate theSQLiteOpenHelper

Declare your database helper as a static instance variable and use the Singleton pattern to guarantee the singleton property. The sample code below should give you a good idea on how to go about designing the DatabaseHelper class correctly.

The static getInstance() method ensures that only one DatabaseHelper will ever exist at any given time. If the sInstance object has not been initialized, one will be created. If one has already been created then it will simply be returned. You should not
initialize your helper object using with new DatabaseHelper(context)! Instead, always use DatabaseHelper.getInstance(context), as it guarantees that only one database helper will exist across the entire application‘s lifecycle.

public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper sInstance; private static final String DATABASE_NAME = "database_name"; private static final String DATABASE_TABLE = "table_name"; private static final int DATABASE_VERSION
= 1; public static synchronized DatabaseHelper getInstance(Context context) { // Use the application context, which will ensure that you // don‘t accidentally leak an Activity‘s context. // See this article for more information: http://bit.ly/6LRzfx if (sInstance
== null) { sInstance = new DatabaseHelper(context.getApplicationContext()); } return sInstance; } /** * Constructor should be private to prevent direct instantiation. * make call to static method "getInstance()" instead. */ private DatabaseHelper(Context context)
{ super(context, DATABASE_NAME, null, DATABASE_VERSION); } }

Approach #2: Wrap the SQLiteDatabase in a ContentProvider

This is also a nice approach. For one, the new CursorLoader class requiresContentProviders, so if you want an Activity or Fragment to implementLoaderManager.LoaderCallbacks<Cursor> with a CursorLoader (as discussed inthis post), you‘ll need to implement
a ContentProvider for your application. Further, you don‘t need to worry about making a singleton database helper withContentProviders. Simply call getContentResolver() from the Activity and the system will take care of everything for you (in other words,
there is no need for designing a Singleton pattern to prevent multiple instances from being created).

Leave a comment if this helped or if you have any questions!

http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html

这个错误出现的原因是因为我在一个数据库查询方法中调用了另一个数据库查询方法,我的数据库查询方法都是在开始的时候获取SQLiteDatabase对象,在结束的时候关闭SQLiteDabse对象,结果内部的数据库查询方法在结束的时候直接关闭了SQLiteDatabase对象,导致外面的数据库查询操作报错,在这里大家不要以为多获取了几个SQLiteDatabase对象就可以了,每个线程只能使用一个SQLiteOpenHelper,也就使得每个线程使用一个SQLiteDatabase对象(多线程操作数据库会报错);

解决办法就是我不再关闭内部数据库查询方法的SQLiteDatbase对象或者将那个方法直接集成到外面的查询方法中,当然,要确保这个查询方法只会出现其他数据库查询方法中,要是单独用这个方法,反而会因为SQLiteDatabase对象没有关闭而报错;

http://blog.csdn.net/zhufuing/article/details/14455823

下面这个方法用了异步思想,但是没有解决我的问题。

【翻译】Android多线程下安全访问数据库

http://zhiweiofli.iteye.com/blog/2041977

原文: https://github.com/dmytrodanylyk/dmytrodanylyk/blob/gh-pages/articles/Concurrent%20Database%20Access.md

Android Sqlite常见异常的原因举例

产生原因:

假如你有A、B两个异步线程操作sqlite数据库。A是读取,B是写入,当A完成读的时候调用close(),而B在这时正在执行写的方法就会出现下面的异常。有人说去掉单例模式可以解决这个问题,但你不能忘记你在怎么单例使用的数据库还是同一个,避免不了。

解决办法:

如果你在一定的时间内需要重复的操作数据库,那么不要调用close()方法,关闭游标就可以了。在你Activity注销或者真正不再需要的时候调用数据库的colse()方法.

http://blog.csdn.net/aaren_jiang/article/details/11781155

时间: 2024-10-03 05:14:18

java.lang.IllegalStateException: attempt to re-open an already-closed object的相关文章

java.lang.IllegalStateException——好头疼

在我东,下下来一个项目总会出现启动不了的问题,这些问题往往在编译的时候发现不了,当你的服务器启动的时候,就是一片片的报错,有些问题可以通过异常的提示信息,判断出来哪里配置错了,但是也有些情况下,从异常的提示信息中压根看不出来具体哪个地方出现问题了,比如下面的这段异常信息,我就不能一下子定位到哪里错了. 八月 05, 2017 11:09:53 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc严重: The we

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.templateEngine

2018-12-25 22:58:28.023 DEBUG 2204 --- [ restartedMain] c.c.c.a.CrawlerAutohomeApplication : Running with Spring Boot v2.1.1.RELEASE, Spring v5.1.3.RELEASE 2018-12-25 22:58:28.039 INFO 2204 --- [ restartedMain] c.c.c.a.CrawlerAutohomeApplication : No

Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.mchange.v2.c3p0.ComboPooledDataSource] from ClassLoader [ParallelWebappClassLoader

Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.mchange.v2.c3p0.ComboPooledDataSource] from ClassLoader [ParallelWebappClassLoader 020-04-11 18:49:17,914 WARN [org.springframework.web.context.support.XmlWebApplicationConte

java.lang.IllegalStateException: Failed to load ApplicationContext

1.错误描述 INFO:2015-02-05 22:14:21[main] - Loading XML bean definitions from class path resource [applicationContext.xml] INFO:2015-02-05 22:14:22[main] - JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning INFO:2015-02-05

java.lang.IllegalStateException: ContainerBase.addChild: start

java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina] Tomcat部署Servlet时出错 caused by: Caused by: java.lang.IllegalArgumentException: Invalid <url-patt

开发中遇到的问题(一)——java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

1.错误描述: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. 2.起因: 在Manifest中设置我的activity全屏 1 <activity android:name=".SplashActivity" 2 android:theme="@android:style/Theme.Black.No

java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already.

java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [META-INF/services/javax.xml.bind.JAXBContext]. 解决方法:先将项目remove,然后停止服务器,到应用程序目录下将部署的应用删除,然后启动服务器,重新部署就ok了 原因:暂不明确,可能是修改后有原来的残留物.

java.lang.IllegalStateException: getWriter() has already been called for this response

java.lang.IllegalStateException: getWriter() has already been called for this response 出现原因: 1.代码中有打开的Response.getWriter(),未关闭 2.再次使用了ServletOutputStream out = response.getOutputStream(); 通过查看代码,response中的usingWriter=true,想办法将该标志位设置为false. response.r

Caused by: java.lang.IllegalStateException: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError

SLF4J: Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError. SLF4J: See also http://www.slf4j.org/codes.html#log4jDelegationLoop for more details.Exception in thread "main" java.lang.Exception