ip696
ip696

Reputation: 7094

Best practice for add items to adapter from LiveData.observe()

I have DAO method returned LiveData<List<Category>>:

LiveData<List<Category>> listLiveData = categoryDao.getAll();

After that I need set this data to my Adapter:

listLiveData.observe(this, categories -> {
      if (categories == null || categories.isEmpty()) {
            price.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.INVISIBLE);
        } else {
            categoryAdapter = new CategoryAdapter(categories);
            categoryAdapter.setOnItemClickListener(new ClickHandler());
            recyclerView.setAdapter(categoryAdapter);
        }
 });

if I have not data in DB I show button for update(get data from server and insert to DB). if I have data I create adapter and set data to it.

After that if I insert some Category to DB I get this:

  1. triggered observe method and get all categories
  2. create new adapter with this data

I think it is very bad practice(create a new adapter for update each item) and I can some way:

  1. Change my adapter and add method addData(List<Category> categories);

    in onCreateView I create adapter: categoryAdapter = new CategoryAdapter(new ArrayList());

then when I get data in observe method I add it to adapter:

adapter.addData(categories); 

and into addData method in loop check each item and if not exist add to list and notify data.

  1. change method

    LiveData> listLiveData = categoryDao.getAll();

to

LiveData<Category> category = categoryDao.getLast();

and add this item to observe method. But I have 2 problems: 1 - How can I add firstly all data? I must implement 2 methods getAll(call wen create adapter) and getLast(call for each insert in DB). 2. How can I write this getLast method?

  1. correct way that you will advise me :)

Upvotes: 5

Views: 5604

Answers (1)

Sachin Chandil
Sachin Chandil

Reputation: 17819

  • Your first step is right, you should create adapter only once in a lifecycle of Fragment or Activity and set the value(list) to adapter whenever you need to change dataset.

  • You should use getAll() method and it is best practice because you have data in local database and that doesn't take longer. If you have long data set then you should use pagination where only limited no. of items are fetched at a time. That can be achieved using LIMIT clause queries in sqlite.

  • And then use notifyDatasetChanged() method. If you want to show a smooth animation for newly inserted items use DiffUtil class to compare list and notify adapter accordingly.

To know how to use DiffUtil, check this out https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00

Hope this helps.

Upvotes: 4

Related Questions