Firebase addValueEventListener sometimes returns null DataSnapshot

My Android app uses Firebase JAVA API which works really well. However, I recently noticed that sometimes I get a null value returned in datasnapshot with this code.

 public void startLeaderboardListener (final String roundID) {
    myClubFirebaseRef.child("/rounds/" + roundID + "/scores/users/").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            JSONArray usersJSONArray = new JSONArray();
            //ToDo : BUG : Returned a null object reference here
            Map<String, JSONObject> usersMap = (HashMap<String, JSONObject>) snapshot.getValue();
            JSONObject usersJSON = new JSONObject(usersMap);
            if (usersMap != null) try {
                Iterator x = usersJSON.keys();
                while (x.hasNext()) {
                    String thisUSerID = (String) x.next();
                    usersJSONArray.put(usersJSON.get(thisUSerID));

                    JSONObject thisUserJSON = usersJSON.getJSONObject(thisUSerID);
                    SQLiteRounds db = new SQLiteRounds(myContext);
                    JSONObject thisUserStatusJSON = thisUserJSON.getJSONObject("status");
                    JSONArray thisUserDataJSON = thisUserJSON.getJSONArray("data");
                    db.updateLocalRoundwithScores(thisUSerID, roundID, thisUserStatusJSON, thisUserDataJSON);
                }
                myScoreListener.onScoreUpdated(usersJSONArray);

            } catch (Throwable t) {
                t.printStackTrace();
                Log.e ("CloudArchery", "Error extracting JSON Data from User Update (ClubFirebase.startLeaderboard");
            }
        }//StartLeaderboard

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.e("CloudArchery", "The read failed (ClubFirebase.startLeaderboard) : " + firebaseError.getMessage());
        }

    });
} //startLeaderboardListene

      

+3


source to share





All Articles