1

我正在从文件中在 android SQLite 数据库中插入行。在 databaseHelper 的 onUpdate 函数中,我调用 insertInDb 函数:

InputStream is = null;
AssetManager assetManager = context.getResources().getAssets();
String fileLine = "";
String[] data;
ContentValues row = new ContentValues();
long rowid;

try {
    is = assetManager.open(filename);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    db.beginTransaction();
    while((fileLine = br.readLine()) != null){
        data = fileLine.split("@-@");
        row.put(QuoteAllEntry.COLUMN_QUOTE, data[0]);
        row.put(QuoteAllEntry.COLUMN_AUTHOR, data[1]);
        row.put(QuoteAllEntry.COLUMN_FAVORITE, 0);
        row.put(QuoteAllEntry.COLUMN_CAT_KEY, data[2]));
        rowid = db.insert(DataContract.QuoteAllEntry.TABLE_NAME, null, row);
    }
    db.setTransactionSuccessful();
}catch (Exception e) {
    e.printStackTrace();
}
finally {
    db.endTransaction();
}

只插入了一行数据,并且是文件的最后一行。出了什么问题?我似乎找不到问题所在。

4

2 回答 2

1

ContentValues row = new ContentValues();在while循环内移动。

此外,您没有关闭导致内存泄漏的输入流。

于 2015-12-14T15:05:49.217 回答
0

这是事务的标准模式,setTransactionSuccessful()在 while 循环内移动

beginTransaction();
try {
//db operations ...

setTransactionSuccessful();
} finally {
endTransaction();
}
于 2015-12-14T14:26:25.377 回答