RecyclerView 在返回到被销毁的 Activity 后变为空

问题描述

我有一个 recyclerview,它从 Firebase 数据库 读取人员列表并将他们显示在布局上。当我第一次访问活动时,一切都按预期进行,但是当我使用 BackButton 完成活动并尝试再次访问该活动时,recyclerview 变为空。 请注意,我尝试通过使用 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()
    }
}

解决方法

问题是回收器视图没有实现 scrollToPosition() 方法。所以通知适配器后,调用scroll方法,代码变为:

// ... 

    adapter.notifyItemInserted(index)
    recview.scrollToPosition(0)

// ...

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...