gpt4 book ai didi

java - close() 从未在 android sqlite 中收到数据库异常时显式调用

转载 作者:行者123 更新时间:2023-12-01 15:17:24 24 4
gpt4 key购买 nike

“InitDatabase()” 被称为 “inserRecord()” 但每次都会显示异常,并且在 insertRecord() 中我也有称为 closeDatabase() ,其中我有关闭 DB(数据库)的代码。

1。插入数据运行时出错:

在程序启动时,我使用 insertRecord() 输入记录,该记录工作正常,但在运行时,当我插入记录时,它返回新行 ID,但是当我 从表中选择 * 时 那么它不会显示最后插入的记录

2。将光标存储在 HashMap 中:

如果该应用程序需要的话,是否可以将光标进一步存储在 HashMap 中?

public SQLiteDatabase initDatabase(){
Log.v("XIG","creating or opening database.");
db_helper= new DatabaseHelper(context,dbname,1);
DB = context.openOrCreateDatabase(dbname,SQLiteDatabase.CREATE_IF_NECESSARY, null);
DB.setVersion(1);
DB.setLocale(Locale.getDefault());
DB.setLockingEnabled(true);
DB = db_helper.getWritableDatabase();
return DB;
}


public void insertRecord(String Table,String columnId[],String value[],String typeOfValue[]){
initDatabase();
Log.v("XIG","creating new record.");
ContentValues new_record = new ContentValues();
for(int i=0; i<columnId.length; i++){
if(typeOfValue[i].equals("INT")){
new_record.put(columnId[i],Integer.parseInt(value[i]));
}
else{
new_record.put(columnId[i],value[i]);
}
}
long rowid;
try{
DB.beginTransaction();
rowid = DB.insert(Table,null,new_record);
DB.setTransactionSuccessful();
}
finally{
DB.endTransaction();
}
Log.v("XIG","inserted rowid in "+Table+": "+rowid);
closeDatabase();
}

异常:

initDatabase() method shows exception :
07-12 13:15:32.415: E/SQLiteDatabase(13643): close() was never explicitly called on database '/data/data/com.app/databases/mydb3'
07-12 13:15:32.415: E/SQLiteDatabase(13643): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

最佳答案

DB.setTransactionSuccessful();之后

你必须使用DB.commit();来提交它,那么它肯定会起作用。

您可以使用下面的代码将光标数据存储到 MashMap 的列表中

 public ArrayList<HashMap<String, String>> select(
String tableName, String[] fields,
String[] selectionArgs) {

Cursor cursor = // get data by firing query
cursor.moveToFirst();

ArrayList<HashMap<String, String>> mapList = new ArrayList<HashMap<String,String>>();

for (int i = 0; i < cursor.getCount(); i++) {

cursor.moveToPosition(i);

HashMap<String, String> map = new HashMap<String, String>();
for (int j = 0; j < fields.length; j++) {
map.put(fields[j], cursor.getString(j));
}
mapList.add(map);
}

return mapList;
}

如果有效,请接受此答案。

关于java - close() 从未在 android sqlite 中收到数据库异常时显式调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com