我从一个文件在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();
}
只插入一行数据,它是文件的最后一行。出了什么问题?我似乎无法找到问题。
答案 0 :(得分:1)
在while循环中移动ContentValues row = new ContentValues();
。
此外,您还没有关闭导致内存泄漏的输入流。
答案 1 :(得分:0)
这是交易的标准模式,在循环中移动setTransactionSuccessful()
beginTransaction();
try {
//db operations ...
setTransactionSuccessful();
} finally {
endTransaction();
}