I want to have an add
button after all my exercise Items like this:
Image of the RecyclerView I want
and I tried Implementing it in my CustomAdapter
like this:
class CustomAdapterExercise(val exerciseList: ArrayList<Exercise>) : RecyclerView.Adapter<CustomAdapterExercise.ViewHolder>() {
val typeAdd = 0
val typeExercise = 1
//this method is returning the view for each item in the list
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapterExercise.ViewHolder {
if (viewType == typeAdd) {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.exercise_layout, parent, false)
return ViewHolder(itemView)
} else if (viewType == typeExercise) {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.add_layout, parent, false)
return ViewHolder(itemView)
}
else{
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.add_layout, parent, false)
return ViewHolder(itemView)
}
}
//this method is binding the data on the list
override fun onBindViewHolder(holder: CustomAdapterExercise.ViewHolder, position: Int) {
holder.bindItems(exerciseList[position])
}
override fun getItemViewType(position: Int): Int {
if (position <= exerciseList.size) {
return typeExercise
} else if (position == exerciseList.size + 1) {
return typeAdd
}
else{
return typeAdd
}
}
//this method is giving the size of the list
override fun getItemCount(): Int {
return exerciseList.size + 1
}
//the class is hodling the list view
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(Exercise: Exercise) {
val exerciseAmount = itemView.findViewById<TextView>(R.id.exerciseAmount)
val exerciseName = itemView.findViewById<TextView>(R.id.exerciseName)
val exerciseWeight = itemView.findViewById<TextView>(R.id.exerciseWeight)
val exerciseSets = itemView.findViewById<TextView>(R.id.exerciseSets)
exerciseAmount.text = Exercise.exAmount
exerciseName.text = Exercise.exName
exerciseWeight.text = Exercise.weight
exerciseSets.text = Exercise.sets
}
}
}
but It crashes as soon as I go to that view and it gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at abyte.fitness.fitnessbyte.CustomAdapterExercise$ViewHolder.bindItems(CustomAdapterExercise.kt:67)
I get that this is because I am assigning text to my add-button but I don't know how to do this differently and make it work.
I have already seen the "duplicate" question when I was searching all day but it is not explained well for a beginner like myself...