This is my code so far.
Fragment to which recylerview is attached.
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRestaurantLandingPage = getActivity().findViewById(R.id.restaurant_activity);
// mRestaurantMenuRecyclerView = view.findViewById(R.id.restaurant_dish_item_recyler_view);
isAvailable = foodItemViewModel.getRestaurantId();
mRestaurantMenuRecyclerView = view.findViewById(R.id.restaurant_dish_recyler_view);
mRestaurantMenuRecyclerView.setHasFixedSize(true);
mRestaurantMenuRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
LinearLayoutManager.VERTICAL, false));
if (!(isAvailable == mRestaurantId)) {
//InsertFoodIAsyncTask insertFoodIAsyncTask = new InsertFoodIAsyncTask();
//insertFoodIAsyncTask.execute(mRestaurantId);
insertFoodItems(mRestaurantId);
} else {
progressDialog.show();
mCategory = foodItemViewModel.getFoodCategories();
for (String category : mCategory) {
foodItems = new ArrayList<>();
foodItems.addAll(foodItemViewModel.getFoodByCategory(category));
RestaurantMenuCategoryModel menuCategoryModel = new RestaurantMenuCategoryModel(category, foodItems);
menuCategoryModels.add(menuCategoryModel);
mRestaurantMenuRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
restaurantMenuCategoryAdapter = new RestaurantMenuCategoryAdapter(getContext(), menuCategoryModels,
mRestaurantLandingPage, foodItemViewModel);
mRestaurantMenuRecyclerView.setAdapter(restaurantMenuCategoryAdapter);
restaurantMenuCategoryAdapter.notifyDataSetChanged();
}
progressDialog.dismiss();
}
foodItemViewModel.getAllLiveFood().observeForever(new Observer<List<FoodItem>>() {
@Override
public void onChanged(@Nullable List<FoodItem> foodItemList) {
}
});
}
private void insertFoodItems(final int restaurantid) {
String mUrl = mApiUrl + "getRestaurantMenu?restaurantId=" + restaurantid;
Log.d("Inside Database ", "from Async Hope it works");
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
mUrl,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, "response length" + response.length());
for (int i = 0; i < response.length(); i++) {
try {
updateRoom Database
} catch (JSONException e) {
e.printStackTrace();
}
}upDateUI();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("JSON Response", error.toString());
}
});
RequestController.getInstance().addToRequestQueue(jsonArrayRequest);
}
private void upDateUI() {
mCategory = foodItemViewModel.getFoodCategories();
for (String category : mCategory) {
foodItems = new ArrayList<>();
foodItems.addAll(foodItemViewModel.getFoodByCategory(category));
RestaurantMenuCategoryModel menuCategoryModel = new RestaurantMenuCategoryModel(category, foodItems);
menuCategoryModels.add(menuCategoryModel);
mRestaurantMenuRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
restaurantMenuCategoryAdapter = new RestaurantMenuCategoryAdapter(getContext(), menuCategoryModels,
mRestaurantLandingPage, foodItemViewModel);
mRestaurantMenuRecyclerView.setAdapter(restaurantMenuCategoryAdapter);
restaurantMenuCategoryAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
RestaurantMainActivity mRestaurantMainActivity = (RestaurantMainActivity) getActivity();
mQueryData = new ArrayList();
mQueryData = mRestaurantMainActivity.getIntentDataForFragments();
mRestaurantId = Integer.parseInt(mQueryData.get(0).toString());
foodItemViewModel = ViewModelProviders.of(this).get(FoodItemViewModel.class);
progressDialog = new ProgressDialog(getActivity());
view = inflater.inflate(R.layout.restaurant_menu_fragment, container, false);
return view;
}
Recyclerview where user can increase or decrease the food count.
holder.mAddToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentItem.setQuantityincart(1);
currentItem.setFoodincart(1);
foodItemViewModel.addFoodToCart(currentItem);
holder.mAddToCart.setVisibility(View.GONE);
holder.mAddButtonQuantityLinearLayout.setVisibility(View.VISIBLE);
holder.mFoodQuantityTextView.setText(String.valueOf(currentItem.getQuantityincart()));
showViewCart();
}
});
holder.mDecreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
currentItem.setQuantityincart(currentItem.getQuantityincart() - 1);
if (currentItem.getQuantityincart() < 1) {
holder.mAddToCart.setVisibility(View.VISIBLE);
holder.mAddButtonQuantityLinearLayout.setVisibility(View.GONE);
currentItem.setFoodincart(0);
foodItemViewModel.decreaseFoodQuantity(currentItem);
}
holder.mFoodQuantityTextView.setText(String.valueOf(currentItem.getQuantityincart()));
foodItemViewModel.decreaseFoodQuantity(currentItem);
showViewCart();
}
});
holder.mIncreaseQuantityButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, "Before Decrease Click Current Food Item Count " + currentItem.getQuantityincart(), Toast.LENGTH_SHORT).show();
currentItem.setQuantityincart(currentItem.getQuantityincart() + 1);
foodItemViewModel.increaseFoodQuantity(currentItem);
holder.mFoodQuantityTextView.setText(String.valueOf(currentItem.getQuantityincart()));
Toast.makeText(mContext, "Before Decrease Click Current Food Item Count " + currentItem.getQuantityincart(), Toast.LENGTH_LONG).show();
showViewCart();
}
});
private void showViewCart() {
mSnackbar = Snackbar.make(mRestaurantLandingPage, "Total Cost ₹ " + foodItemViewModel.getTotalPrice(), Snackbar.LENGTH_INDEFINITE);
mSnackbar.getView().setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
mSnackbar.setActionTextColor(mContext.getResources().getColor(R.color.colorBackground));
mSnackbar.setAction("View Cart", new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent mCartIntent = new Intent(mContext, CartItemsActivity.class);
mContext.startActivity(mCartIntent);
}
});
mSnackbar.show();
}`enter code here`
When User Clicks on snackbar user is routed to CartActivity where user can remove the item or increase or decrease the item which is passed.
В настоящее время, когда пользователь обновляет значение, например, увеличивает или уменьшает или удаляет продукт из корзины в этот момент времени, я обновляю номер дБ.Затем, если пользователь нажимает кнопку «Назад», пользователь перенаправляется на Activity, которая содержит фрагмент и связанный обзор recyler, но представление recyler по-прежнему показывает старые данные, например, количество не сбрасывается, хотя в Db оно обновляется (Room DB).
Я не уверен, как именно использовать оперативные данные и изменяемые данные Room DB в этом сценарии.Заранее спасибо решение или руководство будет полезно