for循环返回空,单击时不显示任何内容

时间:2019-09-12 00:12:52

标签: java android arrays firebase google-cloud-firestore

[Firestore Data image

当我运行程序并单击按钮时,它的意思是从我的数组中选择一个随机索引并显示内容。随机数等在到达for循环时都正常工作,并且不从数组中检索数据

我已经使用谷歌搜索了一段时间,只是在混淆自己尝试不同事物的自我。抱歉,我对Java和android studio非常陌生


 public void onClick(View view) {

        txtDisplay = findViewById ( R.id.textViewDisplay );
        int color = cColorWheel.getColor ();
        txtDisplay.setBackgroundColor ( color );
        //=========================================
        Random rn = new Random ();
        int RN = rn.nextInt ( 14 );
        //========================================================
        FactRef.whereArrayContains ( "facts", RN ).get ()
                .addOnSuccessListener ( new OnSuccessListener<QuerySnapshot> () {

                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        StringBuilder data = new StringBuilder ();
                        for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots) {
                            Fact note = documentSnapshot.toObject ( Fact.Class );
                            note.setDocumentId ( documentSnapshot.getId () );

                            String documentId = note.getDocumentId ();


                            data.append ( "Id:" ).append ( documentId );
                            for (String tag : note.getTags ()) {
                                data.append ( "\n-" ).append ( tag );
                            }
                            data.append ( "\n\n" );
                        }
                        txtDisplay.setText ( data.toString () );


                    }
                } );
    }

任何帮助都会被重视

1 个答案:

答案 0 :(得分:1)

如果您使用以下代码行:

Random rn = new Random();
int RN = rn.nextInt(14);
FactRef.whereArrayContains("facts", RN).get().addOnSuccessListener(/* ... */);

要基于等于0到14之间的数字的索引从facts数组返回一个随机项,请注意这是不可能的。您无法根据特定索引使用RNDFacts查询whereArrayContains()集合。该方法正在搜索与其自身相同的项目。例如,如果要在数组中搜索:

  

超人并非总是飞翔

这是您应该使用的查询:

String fact = "Superman Didn't Always Fly";
FactRef.whereArrayContains("facts", fact).get().addOnSuccessListener(/* ... */);

如果要从facts数组中获取随机项目,则应获取整个文档get the facts array property as a List<String>并使用以下几行:

List<String> facts = (List<String> facts) document.get(facts);
Random rn = new Random();
int RN = rn.nextInt(facts.size());
String fact = facts.get(RN);