1

I'm learning Firebase.

I made global variable String key and called inside of listener and outside of listener and printed it.

The key inside of listener printed

-LBpjFMIPq-kQWyBmqf7

-LBpjJdnQexxf_ilEPbw

-LBpkAIHkLy_JvZ-o0z1

The key outside of listener printed

null

I think it is because of async. I want to have same key value what should I do in this case?

package com.example.happy.firebasetest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;


public class MainActivity extends AppCompatActivity {
    String key;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference ref1 = database.getReference("test");

        ref1.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot datas: dataSnapshot.getChildren()) {
                    key = datas.getKey();
                    System.out.println(key);
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        System.out.println("outside" + key);
    }
}
Community
  • 1
  • 1
JillAndMe
  • 3,989
  • 4
  • 30
  • 57
  • Data is loaded from Firebase asynchronously. By the time you log the key outside of `onDataChange`, the value hasn't loaded yet. You can only access the values reliable *inside* onDataChange. See https://stackoverflow.com/questions/46645811/android-firebase-get-string-from-datasnapshot-to-the-outside, https://stackoverflow.com/questions/40447073/firebase-retrieve-data-null-outside-methodm, and https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93 – Frank van Puffelen May 06 '18 at 16:36

0 Answers0