get random value android firebase java

2020-02-13 01:33发布

问题:

I want to get a random from my list by using push() in java.

Here is my code to store my data:

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

This is what it looks like in my firebase database:

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

This is how I retrieve my data:

        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<DataSnapshot> ds = snapshot.getChildren();
            Iterator<DataSnapshot> ids = ds.iterator();
            Map<String, Object> newPost = (Map<String, Object>) ids.next().getValue();
            String msg = newPost.get("pubMsg").toString();
            disp_msg.setText(msg.toString());

        }

I want to retrieve a random value in my database. For example. Get random value it can either be "Tomorrow is very windy" or "Today is very windy and rainy".

Can you guys help me with some information I can use in java, I'm still inexperienced in other languages. Thank you in advance.

SOLVED

        //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.
           }

回答1:

Find out the number of possible values (numvals) in the database and then use that in

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

and select the "random"th entry in your database.