java - 火力地堡安卓 : Display data randomly

标签 java android database firebase

我在尝试在屏幕上显示一些数据时遇到问题。

我的数据示例:

enter image description here

我想要什么:

我希望能够显示数据-

QUOTE

AUTHOR

在我的两个文本字段上。

但是,我希望在用户访问该页面时随机获取数据。

因此,如果我转到主页并返返回价页面,它可能会显示第 3 个报价,如果我关闭应用程序并再次打开,它可能会显示第 5 个报价。我不想在列表中一次显示它们。

我试过:

How to fetch data from firebase real time database in android

Get random data android firebase database in RecyclerView

我当前的代码:

name = findViewById(R.id.author);
    quote = findViewById(R.id.quote);

    auth = FirebaseAuth.getInstance();
    user = auth.getCurrentUser();

    databaseReference = FirebaseDatabase.getInstance().getReference("Quotes");

    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String authorName = datas.child("AUTHOR").getValue().toString();
                String quoteGiven = datas.child("QUOTE").getValue().toString();

                name.setText(authorName);
                quote.setText(quoteGiven);
            }
        }

最佳答案

找到了为什么它不起作用,它的顺序错误。这是最终答案

name = findViewById(R.id.author);
    quote = findViewById(R.id.quote);
    btn = findViewById(R.id.button);

    auth = FirebaseAuth.getInstance();
    user = auth.getCurrentUser();

    databaseReference = FirebaseDatabase.getInstance().getReference("Quotes");
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            int count = (int) dataSnapshot.getChildrenCount();
            for(DataSnapshot datas: dataSnapshot.getChildren()){
                int rand = new Random().nextInt(count);
                    for (int i = 0; i < rand; i++) {
                        String authorName = datas.child("AUTHOR").getValue().toString();
                        String quoteGiven = datas.child("QUOTE").getValue().toString();
                        name.setText(authorName);
                        quote.setText(quoteGiven);
                    }
            }
        }

关于java - 火力地堡安卓 : Display data randomly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274950/

相关文章:

java - 格式 EEEE、MMMM d、YYYY h :mm:ss a z 的解析器异常

Java多正则表达式搜索

java - Spring-Boot 向 REST 服务添加基本的 http 安全性

javascript - 如何将我的 JavaScript Web 应用程序转换为 Android 应用程序?

android - 是否有 android Intent 将数据添加到 Google keep

java - 如何使用 REPLICA_SET_SECONDARY 类型对 MongoDB 服务器执行写操作?

java - 排除基于 PropertyFileConfig 的 CDI Bean(DeltaSpike,WebSphere 8.5.5)

android - 获取 listView 中所有完整的可见对象

mysql - 将数组数据输入数据库表时遇到困难

database - PostgreSQL 多行插入是全有还是全无?