0

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

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

在程序开始时,我使用insertRecord()输入记录,它工作正常,但是在运行时,当我用来插入记录时,它返回新的行 ID,但是当我select * from table然后它不会显示最后插入的记录

2、在HashMap中存储Cursor:

如果在该应用程序中需要,是否可以将光标进一步存储在哈希图中。

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
4

4 回答 4

1

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;
}

如果可行,请接受此答案。

于 2012-07-12T08:17:06.457 回答
0

关闭应该在 finally 块内。如果有异常就不会发生。

于 2012-07-12T08:29:30.283 回答
0

问题可能不在此函数中。您的程序在某处打开数据库并且在调用此函数之前不关闭它,该函数试图“打开”已经打开的数据库..

正如你的错误日志所说

Application did not close the cursor or database object that was opened here

于 2012-07-12T08:21:28.927 回答
0

不要尝试在每次更新时打开和关闭数据库。

当你的应用程序启动时打开数据库一次,不要费心去关闭它。在整个过程中重用单个数据库连接;通过这种方式,您的代码要简单得多,而且您不会丢失任何东西。

于 2012-07-12T09:58:05.733 回答