これを修正するには、AsyncTaskを内部に持つIntentServiceを作成し、onPause内で呼び出します。現在、エラーなしで動作します。 onPauseのコードは次のとおりです:
Intent saveIntent = new Intent(this, SaveService.class);
startService(saveIntent);
これが私の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