Search code examples
androidfirebasefirebase-realtime-databaseandroid-architecture-componentsandroid-livedata

ViewModel getting called everytime


I am using LiveData and ViewModel with Firebase. I am using below code to show the data in RecyclerView.

public class CategoryActivity extends AppCompatActivity {

@BindView(R.id.toolbar_category)
Toolbar toolbar;
@BindView(R.id.recycler_view_category)
RecyclerView categoryRecyclerView;
private List<Category> categoryList = new ArrayList<>();
private CategoryAdapter mAdapter;
private Context context;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category);
    ButterKnife.bind(this);
    setSupportActionBar(toolbar);
    context = this;

    mAdapter = new CategoryAdapter(categoryList, context);
    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
    categoryRecyclerView.setLayoutManager(mLayoutManager);
    categoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
    categoryRecyclerView.setAdapter(mAdapter);    
    CategoryViewModel categoryViewModel = ViewModelProviders.of(this).get(CategoryViewModel.class);
    LiveData<DataSnapshot> liveData = categoryViewModel.getDataSnapshotLiveData();
    liveData.observe(this, new Observer<DataSnapshot>() {
        @Override
        public void onChanged(@Nullable DataSnapshot dataSnapshot) {

            Log.e("CategoryActivity","inside");
            Iterable<DataSnapshot> dataSnapshotIterable = dataSnapshot.getChildren();
            for (DataSnapshot p : dataSnapshotIterable) {
                Category categoryFromFirebase = p.getValue(Category.class);
                categoryList.add(categoryFromFirebase);
            }
                mAdapter.notifyDataSetChanged();
        }
    });
}
}

My problem is that even if I lock the phone and unlock it, everything gets called again and data gets duplicated in the RecyclerView. I am not able to understand what's the problem. Please help.


Solution

  • Just clear you arraylist before add iteam categoryList.clear();

    liveData.observe(this, new Observer<DataSnapshot>() {
            @Override
            public void onChanged(@Nullable DataSnapshot dataSnapshot) {
    
           categoryList.clear(); //clear your arraylist values before adding
    
                Log.e("CategoryActivity","inside");
                Iterable<DataSnapshot> dataSnapshotIterable = dataSnapshot.getChildren();
                for (DataSnapshot p : dataSnapshotIterable) {
    
                    Category categoryFromFirebase = p.getValue(Category.class);
    
                    categoryList.add(categoryFromFirebase);
    
                }
    
                    mAdapter.notifyDataSetChanged();
            }
        });