Firebase的孩子到阵列(Kotlin)

时间:2018-03-26 14:34:30

标签: android firebase kotlin

早上好,

今天我的项目是与Kotlin firebase有点合作。刚发现一个问题,我似乎找不到任何关于如何将所有孩子存储在一个数组中的好文档,然后我就可以进行“for”循环。

4 个答案:

答案 0 :(得分:0)

试试这个。

 var firebaseDatabase: FirebaseDatabase
            firebaseDatabase = FirebaseDatabase.getInstance();

            progressBar.visibility = ProgressBar.VISIBLE
            firebaseDatabase.getReference("players").addValueEventListener(object: ValueEventListener {
                override fun onDataChange(p0: DataSnapshot?) {

                    Log.d("DAta",p0.toString())

                    progressBar.visibility = ProgressBar.GONE
                    if(p0!!.exists()){
                        for (h in p0.children){
                             val player = h.getValue(Player::class.java)
                            photosList.add(player)
                            adapter.notifyDataSetChanged()
                            Log.d("Data","player is "+player.toString())

                        }
                    }
                }

                override fun onCancelled(p0: DatabaseError?) {
                    Toast.makeText(activity,"Fail to Load Data", Toast.LENGTH_SHORT).show()
                }
            });

答案 1 :(得分:0)

您可以尝试使用此库https://github.com/Link184/Respiration

@FirebaseRepository(dataSnapshotType = MyModel.class,
    persistence = true,
    isAccessPrivate = true,
    children = {PlanEventRepository.USERS_CHILD, FirebaseRepository.USER_ID, PlanEventRepository.PLAN_EVENTS_CHILD})
public class MyRepo extends FirebaseListRepository<MyModel> {
    static final String USERS_CHILD = "users";
    static final String PLAN_EVENTS_CHILD = "events";

    protected MyRepo(Configuration<MyModel> configuration) {
        super(configuration);
    }
}

您可以通过这种方式访问​​您的列表:

//MyRepoBuilder is a generated class by annotation processor and can be accedes only after a successful gradle build. 
MyRepoBuilder.getInstance().subscribeToList(new SubscriberRespiration<List<MyModel>>() {
      @Override
      public void onSuccess(List<MyModel> dataSnapShot) {
          //here is your list =)
      }
  });

不支持Kotlin注释处理尚未,因此您必须在自定义存储库中使用java。

答案 2 :(得分:0)

你想要的只是遍历DataSnapShot的所有孩子吗? 如果是这样,MutableList应该可以工作。 你可以尝试这样的事情。

databaseReference.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        elements = dataSnapshot.children.toMutableList()
        for (element in elements) {
            //your logic
        }
    }
    override fun onCancelled(databaseError: DatabaseError) {}
})

答案 3 :(得分:0)

Firebase有两个存储选项,尚不清楚使用哪个存储选项。在我们的项目中,我们使用FirebaseFirestore,并且保存和检索数组/列表数据非常简单。将对象另存为列表,仅使用toObject。例如,下面查询数据库的所有内容

>>> import random
>>> l = range(1, 30)
>>> 
>>> res = [random.sample(l, 10) for _ in range(4)]
>>> pprint(res)
[[23, 25, 27, 9, 8, 19, 3, 16, 26, 7],
 [6, 16, 5, 8, 22, 20, 15, 10, 12, 13],
 [28, 20, 3, 21, 29, 12, 7, 23, 2, 10],
 [18, 13, 29, 23, 19, 10, 27, 7, 17, 20]]