Jeg fiksede dette ved at oprette en IntentService med en AsyncTask inde i den og kalde den i onPause. Det fungerer fejlfrit nu. Her er koden i onPause:
Intent saveIntent = new Intent(this, SaveService.class);
startService(saveIntent);
Og her er min SaveService-klasse:
public class SaveService extends IntentService
{
private ArrayList<Ingredient> ingredientsArray;
private ArrayList<Unit> unitsArray;
private DatabaseHelper dbHelper;
public SaveService(String name)
{
super(name);
}
public SaveService()
{
super("SaveService");
}
@Override
protected void onHandleIntent(Intent intent)
{
//save data to database
dbHelper = new DatabaseHelper(getApplicationContext());
ingredientsArray = QuickBakeConverterPro.ingredients;
unitsArray = QuickBakeConverterPro.units;
new SaveAllTask().execute();
}
private class SaveAllTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... args)
{
//open database
try
{
dbHelper.openDatabase();
}catch(SQLException sqle)
{
throw sqle;
}
dbHelper.deleteAll();
//add all ingredients & units
for (int i = 0; i < ingredientsArray.size(); i++)
dbHelper.addIngredient(ingredientsArray.get(i));
for (int i = 0; i < unitsArray.size(); i++)
dbHelper.addUnit(unitsArray.get(i));
dbHelper.close();
return null;
}
}//SaveAllTask
}//class SaveService