Search code examples
androidmvvmviewmodelandroid-livedata

ViewModel method does not call every time onCreate method is called


My application fetches data from API and populates the recycler view with food's categories image and name. When I click on any image then another activity will open and the second activity will show a list of food of that category. But when I open any category then it's working for the first time but if I press back or Up button came back to the MainAcivity and tap on any other Category then the food items on the Second activity is not changing(ViewModel's method is not getting called).

See the Full Code on GitHub: https://github.com/harshabhadra/Foodie/tree/master/app/src/main

This is MainAcivity's onClick method. I am sending the category name via Intent:

@Override
public void onItemClick(int item) {

    Intent categoryIntent = new Intent(MainActivity.this, 
    CategoryActivity.class);
    categoryIntent.putExtra("name", foodAdapter.getFood(item));
    startActivity(categoryIntent);
}

This is my second Activity:

Intent intent = getIntent();
Food food = intent.getParcelableExtra("name");
category = food.getFoodName();
setTitle(category);

foodViewModel = ViewModelProviders.of(this).get(FoodViewModel.class);
foodViewModel.getFoodCategory(category).observe(this, new 
Observer<List<FoodCategory>>() {
        @Override
        public void onChanged(List<FoodCategory> foodCategories) {
            if (!foodCategories.isEmpty()) {

                progressBar.setVisibility(View.GONE);
                categoryAdapter = new 
CategoryAdapter(CategoryActivity.this, foodCategories);
                recyclerView.setAdapter(categoryAdapter);

                Log.e(TAG, "Category Name: " + category);
            }else {
                Toast.makeText(CategoryActivity.this, "empty list", 
Toast.LENGTH_SHORT).show();
    }
   }
});

I'm expecting to see a different list of foods in the Second Activity according to the category when I tap on that category in MainAcivity.


Solution

  • What's happening is that you are calling loadData(category) in your repository when categoryData is null, i.e. the first time it runs. Afterwards it returns the same livedata without loading on the new category data.

    You just need to move loadData outside the if. Or what you could actually do is to initialize lazily categoryData and get rid of the if.