4

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.
           }
nothingness
  • 694
  • 3
  • 9
  • 25

1 Answers1

4

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.

Neil Masson
  • 2,609
  • 1
  • 15
  • 23
  • hi thanks for your answer but it doesnt show me how to get the positions of the ids in firebase, it only show me how to get a random digit. – nothingness Jan 27 '15 at 01:20
  • Your code sample shows that you are already using an iterator to look at a DataSnapshot. Just iterate a random number of times to get the required value. – Neil Masson Jan 27 '15 at 13:44