得到随机值android firebase java

我想通过在java中使用push()来从我的列表中随机获取。

这是我存储数据的代码:

Firebase publRef = f.child("Language").child("German").child("Message"); Firebase newPublRef = publRef.push(); Map publ = new HashMap(); publ.put("pubMsg", writeMsgField.getText().toString()); newPublRef.setValue(publ); 

这就是我的firebase数据库中的样子:

 Language German Message -Jf6ShYy7niHrqg_x4Tc: "Tomorrow is very windy" -Jf9v0xHAxINUUANrORU: "Today is very windy and rainy" 

这是我检索数据的方式:

  Firebase f = new Firebase("https://myapp.firebaseio.com/Language/German/Message/"); f.addValueEventListener(new ValueEventListener() { public void onDataChange(DataSnapshot snapshot) { disp_msg = (TextView)findViewById(R.id.display_msg); //disp_msg.setText(snapshot.getValue().toString()); Iterable ds = snapshot.getChildren(); Iterator ids = ds.iterator(); Map newPost = (Map) ids.next().getValue(); String msg = newPost.get("pubMsg").toString(); disp_msg.setText(msg.toString()); } 

我想在我的数据库中检索一个随机值。 例如。 得到随机值它可以是“明天很大风”或“今天风很多雨”。

你们能帮助我一些我可以在java中使用的信息吗,我还缺乏其他语言的经验。 先谢谢你。

解决了

  //getting maximum number of children long allNum = snapshot.getChildrenCount(); int maxNum = (int)allNum; //getting the random integer from number of children int randomNum = new Random().nextInt(maxNum); int count = 0; //has next will check the next value while count is used as a position substitute. while(ids.hasNext() && count < randomNum) { ids.next(); count ++; // used as positioning. } 

找出数据库中可能的值(numvals)的数量,然后使用它

 int random = new Random().nextInt(numvals); 

并选择数据库中的“随机”条目。