Solucioné esto creando un IntentService con una AsyncTask dentro y llamándolo dentro de onPause. Funciona sin errores ahora. Aquí está el código en onPause:
Intent saveIntent = new Intent(this, SaveService.class);
startService(saveIntent);
Y aquí está mi clase SaveService:
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