Reputation: 13
I have a recyclerview that reads from a Firebase database a list of people and displays them on the layout. When I access to the activity for the first time it goes everything as expected, but when I finish the activity with the BackButton and when I try to access again to that activity, the recyclerview becomes empty. Note that I try to add programmatically the people by using a Listener for a SingleValueEvent.
class myActivity : AppCompatActivity() {
private var index = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fisio)
Firebase.database.setPersistenceEnabled(true)
val database = Firebase.database("mydatabase")
val myRef = database.getReference("People")
val peopleList = ArrayList<MyPeopleListAdapter.MyPeopleItem>()
val code = intent.getStringExtra("key")
val recview = findViewById<RecyclerView>(R.id.recyclerViewF)
recview.layoutManager = LinearLayoutManager(this)
val adapter = MyPeopleListAdapter(peopleList)
recview.adapter = adapter
recview.setHasFixedSize(true)
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val ref = snapshot.child(code.toString()).getValue<Map<String, *>>()
val peopleListRef = snapshot.child(code.toString()).child("PeopleList")
peopleListRef.children.forEach {
val hash = it.getValue<Map<String,*>>()
val pId = it.key
val pFull = hash!!["Name"].toString()
val pEmail = hash["Email"].toString()
val pPic = hash["Pic"].toString()
val pS = hash["S"].toString()
peopleList.add(index, MyPeopleListAdapter.MyPeopleItem(
pId.toString(),
pPic,
pFull,
pEmail,
pS))
adapter.notifyItemInserted(index)
index += 1
}
}
override fun onCancelled(error: DatabaseError) {
println(error.message)
}
})
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
}
Upvotes: 0
Views: 267
Reputation: 13
The problem was that the recycler view didn't had a scrollToPosition() method implemented. So after the adapter is notified, the scroll method is called and the code becomes:
// ...
adapter.notifyItemInserted(index)
recview.scrollToPosition(0)
// ...
Upvotes: 1