I can not set an isfavorites value by clicking Add to Favorites . Android Studio displays a null pointer exception for ringTonesDao . I do not know how to fix this error. On the other hand, because ringTonesDao is an interface, if I set its value to new RingTonesDao, I have to set all its functions.
this is RingTonesAdapter
//Imports and Package name
public class RingTonesAdapter extends
RecyclerView.Adapter<RingTonesAdapter.ringTonesViewHolder> {
private List<RingTones> ringTonesList;
RingTonesDao ringTonesDao; // <--This is null in logcat
public RingTonesAdapter(List<RingTones> ringTonesList) {
this.ringTonesList = ringTonesList;
}
@NonNull
@Override
public ringTonesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.actv_main_list,
parent, false);
return new ringTonesViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ringTonesViewHolder holder, int position) {
//Set RingTone name to TextView
//Set RingTone Btn
//Set Alarm Btn
//Set Notification Btn
//Add To Favorites Btn
if (ringTonesList.get(position).isFavorite()) {
holder.btn_addToFavorites.setImageResource(R.drawable.ic_favorites);
} else {
holder.btn_addToFavorites.setImageResource(R.drawable.ic_addtofavorites);
}
holder.btn_addToFavorites.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Long id = ringTonesList.get(position).getId();
ringTonesDao.update(true,id);
}catch (NullPointerException e){
Toast.makeText(v.getContext(),"Null Pointer
Exception",Toast.LENGTH_LONG).show();
}
}
});
//Set Play Btn
//ringTonesViewHolder and count items
and this is RingTonesDao
//import and package
@Dao
public interface RingTonesDao {
@Insert
Long add(RingTones ringTones);
@Delete
int delete(RingTones ringTones);
@Query("SELECT * FROM tbl_ringtones")
List<RingTones> getRingTones();
@Query("SELECT * FROM tbl_ringtones WHERE favorites>0 ")
List<RingTones> favorites();
@Query("DELETE FROM tbl_ringtones")
void deleteAll();
@Query("UPDATE tbl_ringtones SET favorites=:favorites WHERE id=:id")
int update (Boolean favorites ,Long id);
}
CodePudding user response:
You need to do something like this
DatabaseClient.getInstance(v.getContext()).getAppDatabase()
.RingTonesDao()
.update(true,id);
read more how to use Rom database : from this example
also there is a difference between Boolean and boolean in Java,
in your case try to use `boolean` instead `Boolean` in your update function.