如何从android中的firebase数据库中获取随机对象? [英] How to get a random object from firebase database in android?

查看:99
本文介绍了如何从android中的firebase数据库中获取随机对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Android应用,我需要从一个孩子的firebase中获取一个随机对象?如何在java中做到这一点?

I am working on an Android app, where I need to get a random object from firebase from a child? How to do it in java?

推荐答案

这就是我要做的,假设我有一个有n个对象的孩子:

This is how I would do it, assuming I had a child with n objects:

如果我不知道n的值,我会首先在我的监听器中执行此操作以获取对象的总数:

If I didn't know how the value of n, I would first do this in my listener to get the total number of objects:

                long n = dataSnapshot.getChildrenCount();

然后我会生成一个0到n之间的随机整数i。如果你不知道如何做到这一点,谷歌吧。

Then I would generate a random integer, i, between 0 and n. If you don't know how to do this, Google it.

最后,我会从孩子那里得到第i项:

Finally, I would get the ith item from the child:

            final ArrayList<MyObject> objects = new ArrayList<>();
            for (DataSnapshot child : children) {
                MyObject object = child.getValue(MyObject.class);
                objects.add(object);
            }
            MyObject objectToUse = objects.get(i);

MyObject显然应该是你正在使用的任何类。

"MyObject" should obviously be whatever class you're using.

我错过了什么吗?有一个更好的方法吗?我对Android很新,对Firebase来说还是新手,所以我要说的话就是用大量的盐哈哈。

Am I missing something? Is there a better way to do this? I'm pretty new to Android and very new to Firebase so take what I have to say with a big grain of salt haha.

这篇关于如何从android中的firebase数据库中获取随机对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆