0

I've been facing a weird occurrence in my android project.

In onCreate method, I'm able to get the user data correctly, but after that calling the same function again returns null & I've been unable to decipher why.

@Override
onCreate(){
  getUserStats(this);
}

 private void getUserStats(Context context) {
    FirebaseDatabase.getInstance()
            .getReference(DatabaseReferences.USERS) //This is just a constant
            .child("just_an_example")
            .get()
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    DataSnapshot result = task.getResult();

                    if (result != null && result.exists()) {
                        Map<String, Object> mainMap = (Map<String, Object>) result.getValue();

                        Log.i("MAIN_USER_MP: ", String.valueOf(mainMap));

                        Toast.makeText(context, "result is there", Toast.LENGTH_LONG).show();

                        if (mainMap != null) {
                            Toast.makeText(context, "main map is there", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(context, "map not there", Toast.LENGTH_SHORT).show();
                        }

                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getUserStats(TuningActivity.this);
                            }
                        },10000);
                    } else {
                        Toast.makeText(context, "result is empty", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    getUserStats(context);
                }
            });
 }

After the task is completed, there's a handler inside to call the method again, after some delay. (This is not the purpose of the project but just for demonstration)

Point to note The 1st call runs successfully & the toast "Main map is there" is shown but subsequent calls after that all fail & the toast "result is empty" is shown.

Any idea what the issue could be? (I've tried also using an Event listener & checking that persistence isn't enabled but still nothing works)

Boron
  • 99
  • 10
  • 34
  • Can you add some logs for more info.. – Dev007 Nov 13 '22 at 06:20
  • That is not how you should interact with Firenase. The Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Nov 14 '22 at 09:13

0 Answers0