1

I want to get a single value in my database, but i find it hard to pass a single string. Here is my code:

FirebaseUser user = firebaseAuth.getCurrentUser();
            databaseReference = FirebaseDatabase.getInstance().getReference("USERS").child(user.getUid()).child("name");

            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String name = (String) dataSnapshot.getValue();
                    editTextName.setText(name);

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

            String name2 = editTextName.getText().toString().trim();

How can i access string name outside of this? I edited my code by it says that

    invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
  • Firebase loads data asynchronously. It's best to embrace that and modify your code to deal with it. See https://stackoverflow.com/questions/33203379/setting-singleton-property-value-in-firebase-listener – Frank van Puffelen May 24 '17 at 02:50

1 Answers1

0

The short answer would be a member variable, however it'll be null until the onDataChange method actually assigns it (which could be never if you have no network connection)

Where do you need the value? In a TextView? Just edit the TextView directly from onDataChange

Need something more complex, call a separate method from onDataChange and pass in your parameters.

Don't force yourself back into synchronous code

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245