I've been looking at the firebase documentation and tried to make firebase work with an android app I'm building.
All the code examples I could find show how to get a value, then immediately print it within the firebase ValueEventListener inner class. I would like to get the values and store them in an array for later use.
What I try to do is when a user clicks the highscore button the client gets the current scoreboard from firebase, and sends that list to the highscoreboard class.
UPDATE: I have been able to retrieve the data now but there is a behavior that confuses me greatly. If the user clicks the highscorebutton the scores list gets populated and highscore class is correctly showing 10 elements. If I exit the scoreboard and enter it again it will now show all scores twice (understandably so, as I am just adding to the same list). But any calls to scores.clear() or scores = new ArrayList(); between the two clicks results in scores being empty even after the second click (I assumed that populating scores, then emptying it and repopulating it would leave 10 items in there) This behavior was the reason I thought my scores array never got populate when first posting here as I had a scores.clear() call inside the load function since I didn't want to duplicate values. If anyone is able to explain why this happens that would be fantastic.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<Score> scores;
Firebase myFirebase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
myFirebase = new Firebase(FirebaseURL);
scores = new ArrayList<Score>();
loadScoresFromFireBase();
}
public void loadScoresFromFireBase() {
String entry = "";
for (int i = 0; i < 10; i++) {
entry = "Name_" + i;
myFirebase.child("users").child(entry).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//getValue correctly returns a Score object
scores.add(snapshot.getValue(Score.class));
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//....
if ( id == 2) {
Intent intent = new Intent(getApplicationContext(), ScoreBoard.class);
Bundle bundle = new Bundle();
//calling scores.clear() here leaves the scores array empty even though loadscores is called afterwards.
loadScoresFromFireBase();
Collections.sort(scores);
bundle.putSerializable("players", scores);
intent.putExtra("players", bundle);
startActivityForResult(intent, 0);
}
}
}