1

I'm inserting rows in android SQLite database from a file. In the onUpdate function in the databaseHelper I call the insertInDb function:

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

Only one row of data is inserted, and it is the last row of the file. What is going wrong? I can't seem to find the problem.

Christoph
  • 33
  • 3
  • No exception is fired? Also can you put the file you are using. Especially the first lines where process breaks? – Maksim Luzik Dec 14 '15 at 14:20
  • *Only one row of data is inserted, and it is the last row of the file* ... **then the file has only one row** ... `db.setTransactionSuccessful();` is last and without this the data would not be added ... but last is added so there was no exception inside try ... so ... there is no other possibility than having only one row in the file – Selvin Dec 14 '15 at 14:22
  • there is a good chance that changing the `row` object after you passed it to the db object is not a good idea. – njzk2 Dec 14 '15 at 15:12

2 Answers2

1

Move ContentValues row = new ContentValues(); inside the while-loop.

Also you're not closing the input stream which results in memory leak.

frogatto
  • 28,539
  • 11
  • 83
  • 129
0

This is standard pattern for transactions, move setTransactionSuccessful() inside while loop

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

setTransactionSuccessful();
} finally {
endTransaction();
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
khyper
  • 124
  • 1
  • 6
  • db.setTransactionSuccessful(); is inside the try {} but not inside the while loop. Somehow only one row is inserted in the database and I can't seem to figure out why. – Christoph Dec 14 '15 at 14:41