Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

get random value android firebase java

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.
           }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...