美好的一天,我的小部件应用程序上的sqlite数据库存在此问题,即使我明确地调用它也永远不会关闭。我得到这个logcat错误
02-26 00:49:42.070: E/Database(18049): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
由于某种原因,当我得到一个游标并调用getCount()方法时,它总是递增,同时也添加了最后一个值。例如..如果我得到游标并且getCount()方法从列返回值5,我稍后删除小部件。当我再次添加小部件并查询我知道值为6的不同列时,我将从光标返回11作为返回值。 getCount()方法。它就像光标一样,数据库永远不会关闭。任何想法可能是错的?...
方法:
private void setTag(String tag){
WeatherImageDB weatherimagedb = new WeatherImageDB(this); // get logcat error on this line
weatherimagedb.open();
ArrayList<String> image_list = new ArrayList<String>();
image_list.clear();
if(weatherimagedb.open() != null){
Cursor cursor = weatherimagedb.retrieveTag(tag);
Log.d(TAG, "size is " + cursor.getCount()); // this always gets incremented with also the last value added
if(cursor.moveToFirst()){
do{
image_list.add(cursor.getString(cursor.getColumnIndex(tag)));
//System.out.println("imagelisted!!");
}
while(cursor.moveToNext());
}
//do other stuffs here with arraylist and then clear
}
image_list.clear();
cursor.close();
weatherimagedb.close();
}
和数据库类中的代码:
private final Context mcontext;
private DBHelper dbhelper;
private SQLiteDatabase db;
public WeatherImageDB(Context context){
mcontext = context;
dbhelper = new DBHelper(mcontext);
}
public class DBHelper extends SQLiteOpenHelper {
DBHelper(Context context){
super(context, IMAGE_DB, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS imagetags");
onCreate(db);
}
}
public WeatherImageDB open() throws SQLException {
try{
db = dbhelper.getWritableDatabase();
}catch(SQLException e){
db = dbhelper.getReadableDatabase();
}
return this;
}
public void close(){
Log.d(TAG, "calling close on Database Object here");
if(dbhelper != null){
dbhelper.close();
db.close();
}
}
public long tagImage(String pathname, ContentValues val){
return db.insert(DATABASE_TABLE, null, val);
}
public boolean deleteTag(String entry ){
return db.delete(DATABASE_TABLE, null, null) >0;
}
public Cursor retrieveTag(String tag){
//open();
String[] condition = {tag};
Cursor cursor = db.query(DATABASE_TABLE, condition, null, null, null, null, null);
return cursor;
}
}
答案 0 :(得分:1)
如果只是循环,你声明的游标范围将在内部....我认为可能有一些其他全局对象与“游标”同名......
if(weatherimagedb.open() != null){
Cursor cursor = weatherimagedb.retrieveTag(tag);
//some stuff--> make sure there are no return statements in this part.
//If any return statement exists close the cursor and then execute return
//it should be closed here
cursor.close();
}
//You are closing outside if loop which is holding reference of some other cursor
cursor.close();