Reputation: 2725
I have a function that adds up numbers from a SQLLite database and then writes a total in that same database. I am doing this in a background task while the main activity waits.
This works properly for some time, but fails with the below, usually about halfway through the loop:
Unable to open database file (code 14):, while compiling: PRAGMA journal_mode
This happens at a different line in the database each time, so I don't think its one entry causing the error.
My code---
Activity:
...
calculateStats();
...
public void calculateStats(final String MY_GROUP){
calculateTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Looper.prepare();
StatCalculator calculator = new StatCalculator();
calculator.writeTotalA(MY_GROUP);
calculator.writeTotalB(MY_GROUP);
calculator = null;
return null;
}
@Override
protected void onPostExecute(Void result) {
}
};
calculateTask.execute(null, null, null);
}
StatCalculator:
public void writeTotalB(String my_group){
DatabaseManager db = new DatabaseManager(this);
DB_GROUP = "DB" + my_group+ ".DB";
SQLiteDatabase groupDB = SQLiteDatabase.openDatabase(DB_PATH + DB_GROUP, null, SQLiteDatabase.OPEN_READWRITE);
Cursor groupCursor = groupDB .query("ItemTable", null, null, null, null, null, null);
if (groupCursor != null ) {
for (int i = 0; i < groupCursor .getCount(); i++) {
...
//calculating total here (totalPoints)
...
//write total to database:
db.update_byID(DB_GROUP , id, "Total", totalPoints);
}
}
groupDB .close();
groupCursor.close();
db = null;
}
The code makes it entirely through calculator.writeTotalA(MY_GROUP) successfully. The crash always takes place halfway through calculator.writeTotalB(MY_GROUP)
I am not sure if this is because I am reading and writing to this database at the same time or what. I would think it would crash sooner if that was the case.
Any help would be greatly appreciated.
Upvotes: 1
Views: 2217
Reputation: 2725
Got it.
The method
db.update_byID(DB_GROUP , id, "Total", totalPoints);
was opening a new instance of the database for each entry and then not closing it.
Upvotes: 2