Skip to content
Advertisement

Implement favorites list with room library

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:

enter image description here

Advertisement

Answer

Try to use thread or Asyc.

Simple example

Thread thread = new Thread() {  
    @Override
    public void run() {
        try {
            //your code 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
thread.start();
10 People found this is helpful
Advertisement