I have a RecyclerView, my adapter class works when the data is added to myModel objects from an array of string resources and floats, but not when these strings are retrieved from firestore. I have done this with textViews in other parts of my application fine. At first I tried using toObject<Model>()
to populate the list passed to my adapter and now I have manually got the data from the hashMap. I have used snackbars to ensure the data is in the list that is passed to my adapter. I have tried overriding the onStart()
and onstop()
to listen for changes to the database but mAdapter
is a local variable in oncreate()
and it is not important that the data in this recycler view updates in realtime, updating when the activity launches is plenty.
This doesn't work:
collection.get().addOnSuccessListener { querySnapshot ->
for (i in 0 until querySnapshot.size()){
val data = querySnapshot.documents[i].data
val Model = Model()
val name = data!!["Name"].toString()
val rating = data!!["Rating"].toString().toFloat()
Model.Name= name
Model.Rating = rating
list.add(Model)
This does:
val myImageNameList = arrayOf(R.string.1, R.string.2, R.string.cafe_3, R.string.4, R.string.5, R.string.6, R.string.7, R.8)
val myImageRatingList = arrayOf(2.4f, 4.1f, 3.6f, 3.4f, 2.8f, 1.9f, 4.1f, 3.9f )
for (i in 0..7){
val model = Model()
model.Name = getString(myImageNameList[i])
model.Rating = myImageRatingList[i]
list.add(model)
}
Adapter class excerpt:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val v = inflater.inflate(R.layout.row_layout, parent, false)
return ViewHolder(v)
}
//bind the data to child views of the ViewHolder
override fun onBindViewHolder(holder: Adapter.ViewHolder, position: Int) {
val info = imageModelArrayList[position]
holder.txtMsg.text = info.Name
holder.ratingbar.rating = info.Rating
holder.ratingDecimal.text = "("+ info.Rating + ")"
}
//get the max size of the recycler view
override fun getItemCount(): Int {
return imageModelArrayList.size
}
inner class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView), View.OnClickListener{
var txtMsg = itemView.findViewById<View>(R.id.firstLine) as TextView
var ratingbar = itemView.findViewById<View>(R.id.rating) as RatingBar
I am confused why the second way of creating model objects works but the first does not, as far as I know in both instances I am creating a model object and assigning its fields with a string and afloat, just in the first example the string and float happen to have come from the firestorm.
edit
the list is passed when instantiating myAdapter as param imageModelArrayList
val recyclerView = findViewById<View>(R.id.recycler_view) as RecyclerView
val layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
val imageModelArrayList = populateList()
val mAdapter = Adapter(imageModelArrayList)
recyclerView.adapter = mAdapter