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:
- triggered observe method and get all categories
- 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:
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.
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?
- correct way that you will advise me :)