I want to implement a list of the user’s favorite news for a news app using the room library, but the app crashes
Thank you for your help (:
DataBase:
I could not put the code, I used the photo:
enter image description here
Dao:
@Dao
public interface DataDao {
@Insert
void insert_list_fav(FavModel favModel);
@Delete
void delete_fav(FavModel favModel);
@Query("SELECT * FROM tbl_fav")
LiveData<List<FavModel>> getFavList();
@Query("SELECT EXISTS (SELECT 1 FROM tbl_fav WHERE id=:id)")
int isFav(int id);
}
AdapterNews:
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
LastNewsModel model= dataModels.get(position);
///////It is added to the list here
holder.save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FavModel favModel=new FavModel();
int id=model.getId();
String title=model.getTitle();
String desc=model.getDescription();
String pic=model.getPic();
String date=model.getDate();
favModel.setId(id);
favModel.setTitle(title);
favModel.setDate(date);
favModel.setDescription(desc);
favModel.setPic(pic);
if (DataBase.getDataBase(context).getDao().isFav(id)!=1){
holder.save.setImageResource(R.drawable.ic_saved);
DataBase.getDataBase(context).getDao().insert_list_fav(favModel);
}else {
holder.save.setImageResource(R.drawable.ic_save);
DataBase.getDataBase(context).getDao().delete_fav(favModel);
}
}
});
}
Erro:
2
Answers
Try to use thread or Asyc.
Simple example
This is due to you’re trying to do database transaction on Main thread which can be heavy sometimes depending on situation that’s why it’s best to use background thread to do this kind of task.
why it’s like this
UI or Main thread is used for showing UI where your user can interact with your app. so loading stuffs like data from Database can be quite heavy sometimes which will end up freezing or in terms of android it can show ANR (App Not Responding) which is not quite good user experience so use other thread other than UI to do heavy thread blocking task.
for e.g.