Я делаю приложение для рецептов, где я получаю список рецептов с сайта с JSON.
Я добавляю рецепты в ArrayList, а затем пытаюсь добавить их в базу данных. Когда я сохраняю состояние приложения, я всегда получаю сообщение о том, что мой ArrayList равен нулю, а я заполняю его в postExecute моего AsyncTask
Это мой код
открытый класс MainActivity расширяет AppCompatActivity, реализует LifecycleOwner {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private ArrayList<Recipe> mRecipes;
private AppDatabase mDb;
private Recipe recipe;
private boolean isAlreadyInDB;
private static final String RECIPE_LIST = "instanceRecipeList";
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mRecipes != null) {
outState.putParcelableArrayList(RECIPE_LIST, mRecipes);
}
super.onSaveInstanceState(outState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null && savedInstanceState.containsKey(RECIPE_LIST)) {
mRecipes = savedInstanceState.getParcelableArrayList(RECIPE_LIST);
Log.d(LOG_TAG, "mymessage mRecipes are " + mRecipes);
setFragment();
}
Log.d(LOG_TAG, "mymessage mRecipes are " + mRecipes);
mDb = AppDatabase.getInstance(getApplicationContext());
if (mRecipes != null) {
setFragment();
} else {
GetRecipes getRecipes = new GetRecipes();
getRecipes.execute();
}
}
private void setFragment() {
RecipeListFragment recipeListFragment = new RecipeListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.placeholder, recipeListFragment)
.commit();
Log.d(LOG_TAG, "mymessage fragment set");
}
private class GetRecipes extends AsyncTask<URL, Void, String> {
@Override
protected String doInBackground(URL... urls) {
URL searchRecipeObjectUrl = NetworkUtils.createUrl();
String jsonString = "";
try {
jsonString = NetworkUtils.makeHttpRequest(searchRecipeObjectUrl);
} catch (IOException e) {
Log.e(LOG_TAG, "mymessage Problem making the HTTP request.", e);
}
return jsonString;
}
@Override
protected void onPostExecute(String jsonString) {
mRecipes = JsonUtils.extractFeatureFromJson(jsonString);
Log.d(LOG_TAG, "mymessage mRecipes onPostExecute " + mRecipes);
AppExecutors.getInstance().diskIO().execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < mRecipes.size(); i++) {
recipe = mRecipes.get(i);
String recipeName = recipe.getRecipeName();
if (!isRecipeInDB(recipeName)) {
mDb.recipesDao().insertRecipe(recipe);
Log.d(LOG_TAG, "mymessage adding to db " + recipeName);
Log.d(LOG_TAG, "mymessage recipes are" + mDb.recipesDao().loadAllRecipes());
} else {
Log.d(LOG_TAG, "mymessage recipe is already in db " + recipeName);
}
}
}
});
}
}
public boolean isRecipeInDB(String recipeName) {
LiveData<String> recipeIsInDB = mDb.recipesDao().searchRecipesByName(recipeName);
recipeIsInDB.observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String nameChecked) {
if (nameChecked != null) {
isAlreadyInDB = true;
} else if (nameChecked == null) {
isAlreadyInDB = false;
}
}
});
return isAlreadyInDB;
}
}
Я ожидал бы добавить фрагмент с отображаемыми данными БД, но он всегда пуст и не будет ничего показывать, поскольку ArrayList всегда равен нулю.
Не обращайте внимания на все это, я пытался отладить.