firebase listview显示空白页面

时间:2017-12-17 15:21:39

标签: listview firebase arraylist firebase-realtime-database kotlin

我的应用在从arraylist的firebase中检索数据后显示空白页面。 下面是我的代码,它在运行时没有显示任何错误

class Main4Activity : AppCompatActivity() {
        private lateinit var data : ListView
       lateinit var arraylst:ArrayList<String>
    lateinit var ref :DatabaseReference

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main4)
        data =findViewById(R.id.abcd)
        arraylst = arrayListOf()
         val  ref = FirebaseDatabase.getInstance().getReference().child("User")
         val adptr = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arraylst)
        data.adapter = adptr
        ref.addChildEventListener(object :ChildEventListener{
            override fun onCancelled(p0: DatabaseError?) {}
            override fun onChildMoved(p0: DataSnapshot?, p1: String?) {}
            override fun onChildChanged(p0: DataSnapshot?, p1: String?) {}

            override fun onChildAdded(p0: DataSnapshot?, p1: String?) {

                if (p0!!.exists()) {
                    for (h in p0.children) {
                        adptr.clear()
                        val rdata = h.getValue(String::class.java)
                        arraylst.add(rdata!!)
                        adptr.notifyDataSetChanged()

                    }
                }
            }
              override fun onChildRemoved(p0: DataSnapshot?) {}

        })

该应用不会显示任何错误,但列表视图项目为空白

2 个答案:

答案 0 :(得分:0)

如果你想要一个子集合,你可以使用ValuEventListener。

或者像那样使用......

override fun onChildAdded(dataSnapShot: DataSnapshot?, p1: String?) {
    dataSnapShot?.getValue<Model>(Model::class.java)?.let { model -> 
        modelList.add(model) 
        adaptr.notifyItemInserted(modelList.size())
    }
}


override fun onChildRemoved(dataSnapShot: DataSnapshot?) {
    dataSnapShot?.getValue<Model>(Model::class.java)?.let { model -> 
        modelList.remove(model)
        adaptr.notifyItemRemoved(modelList.size())
    }
}

答案 1 :(得分:0)

使用此代码从数据库中获取值。

 val reference = database.getReference.child("user")
    reference.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
          var s: String = dataSnapshot.value as String
            Log.e(TAG, "Data : value"+s)
        }

        override fun onCancelled(databaseError: DatabaseError) {
            Log.e(TAG, "onCancelled:kkkkkkk ")
        }
    })