[Firestore Data Image
当我运行程序并单击按钮时,它意味着从我的数组中选择一个随机索引并显示内容。随机数等在到达for循环时都在工作,并且它没有从数组中检索到任何数据
我已经在谷歌上搜索了一段时间,只是让我自己混淆了尝试不同的事情. 对不起,我对Java和Android工作室很陌生
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 ( "nn" );
}
txtDisplay.setText ( data.toString () );
}
} );
}
任何帮助将不胜感激
如果您使用以下代码行:
Random rn = new Random();
int RN = rn.nextInt(14);
FactRef.whereArrayContains("facts", RN).get().addOnSuccessListener(/* ... */);
要根据等于 0 到 14 之间的数字的索引从facts
数组中返回一个随机项目,请不要说这是不可能的。无法使用基于特定索引的whereArrayContains()
查询RNDFacts
集合。该方法搜索与它本身的项目相等的项目。例如,如果要在数组中搜索:
超人并不总是会飞
这是您应该使用的查询:
String fact = "Superman Didn't Always Fly";
FactRef.whereArrayContains("facts", fact).get().addOnSuccessListener(/* ... */);
如果要从facts
数组中获取随机项,则应获取整个文档,获取facts
数组属性作为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);