Eu consertei isso criando um IntentService com um AsyncTask dentro dele e chamando-o dentro de onPause. Funciona sem erros agora. Aqui está o código em onPause:
Intent saveIntent = new Intent(this, SaveService.class);
startService(saveIntent);
E aqui está minha classe 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