I have set up an activity for my users to input messages into Firebase database and another activity to recall the messages at random. However I couldn't seem to get the random method going... the recall method just call the same messages over and over again on click.
I am using and editing the method that username nothingness posted here get random value android firebase java so I don't actually understand how it works...
Here's the code to write to the database:
public class PostActivity extends AppCompatActivity {
private EditText PostField;
private Button postSubmit;
private DatabaseReference mDatabasePosts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
postSubmit = (Button)findViewById(R.id.postSubmit);
postField = (EditText)findViewById(R.id.postField);
mDatabasePosts = FirebaseDatabase.getInstance().getReference().child("posts");
postSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startPosting();
}
private void startPosting() {
final String postVal = postField.getText().toString().trim();
if (!TextUtils.isEmpty(postVal)) {
//post creation
DatabaseReference newPost = mDatabasePosts.push();
newPost.setValue(postVal);
Toast.makeText(PostActivity.this, "Post registered", Toast.LENGTH_SHORT).show();
startActivity(new Intent(PostActivity.this, HomeActivity.class));
}
}
});
}
}
nothing fancy there...
on the retrieving activity, I have a button that will display a toast randomly (well... at least the goal was to) of the texts written to the database... here's the code for that activity:
DatabaseReference mPost;
mPost = FirebaseDatabase.getInstance().getReference().child("posts");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPost.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long allNum = dataSnapshot.getChildrenCount();
int maxNum = (int)allNum;
int randomNum = new Random().nextInt(maxNum);
int count = 0;
Iterable<DataSnapshot> ds = dataSnapshot.getChildren();
Iterator<DataSnapshot> ids = ds.iterator();
String newPost = (String) ids.next().getValue();
while(ids.hasNext() && count < randomNum) {
ids.next();
count ++; // used as positioning.
}
Toast.makeText(HomeActivity.this, newPost,Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
The Database looks like this:
posts
L random key: "text 1"
L random key: "text 2"
L random key: "text 3"
L random key: "text 4"
L random key: "text 5"
L random key: "text 6"
So at the moment, everytime i click on the button... it keeps on calling "text 1" I want it to call text 1 and 2 alternately and randomly...
Can anyone help me with this?