I am trying to create a RecyclerView of String List. But I am unable to get the data into the recyclerView. I am able to create the string ArrayList. I have checked it.
Here is my adapter code:-
class SearchPlaceAdapter(
private var mContext: Context,
private var mPlaces: List<String>,
private var isFragment: Boolean = false,
): RecyclerView.Adapter<SearchPlaceAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutInflater.from(mContext).inflate(R.layout.rv_search_place, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.place.text = mPlaces[position]
}
override fun getItemCount(): Int {
return mPlaces.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var place: TextView =itemView.findViewById(R.id.searchPlaceTV)
}
}
here is my fragment code:-
placesRecyclerview.setHasFixedSize(true)
placesRecyclerview.layoutManager = LinearLayoutManager(context)
placesList = ArrayList()
placesAdapter =
context?.let { SearchPlaceAdapter(it, placesList as ArrayList<String>, true) }
placesRecyclerview.adapter = placesAdapter
searchButton.setOnClickListener {
searchPlaces()
}
private fun searchPlaces() {
val placesRef = FirebaseDatabase.getInstance().reference.child("Places")
placesRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(datasnapshot: DataSnapshot) {
if (datasnapshot.exists()) {
(placesList as ArrayList<String>).clear()
for (snapshot in datasnapshot.children) {
(placesList as ArrayList<String>).add(snapshot.key!!)
}
}
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(context, "Error Occurred.", Toast.LENGTH_LONG).show()
}
})
}
here is the JSON snippet:-
"Places": {
"India": true
}
I don't know why I am not able to get the data. I have tried everything but it is not working.
CodePudding user response:
When you finished getting the data from the Realtime Database, actually when your placesList
already contains all the objects that are returned by your query, then you have one more operation to perform, which is to inform the adapter about the changes using:
for (snapshot in datasnapshot.children) {
(placesList as ArrayList<String>).add(snapshot.key!!)
}
placesAdapter.notifyDataSetChanged(); //Notify the adapter.
As you can see, the last line of code should be added right after the for loop ends.