Sanju
Sanju

Reputation: 115

Make a method in Java return a variable initialized in inner class

I have a method

public String getUsername(String uid){
       uid= auth.getCurrentUser().getUid();
        DatabaseReference uidRef = mFirebaseuser.child(uid);
        uidRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("TAG", ""+dataSnapshot);
                String username=dataSnapshot.child("username").getValue(String.class);
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("what"+databaseError);
            }
        });
        return username;
    }

I want getUsername to return the string username which is initialized in inner class but I don't have access to it, also I cant modify onDataChange since its overriden. If I initialize username in getUsername method before the inner class I have to make it final and then won't be able to set its value in onDataChange please help me to get a work around this.

Upvotes: 2

Views: 108

Answers (3)

Infamous
Infamous

Reputation: 754

One workaround to this is to make a one element array and return the value of it. It's kinda ugly, but it works!

public String getUsername(String uid){
   uid= auth.getCurrentUser().getUid();

   final String[] username = new String[1]; // final makes it accessible inside the inner class

    DatabaseReference uidRef = mFirebaseuser.child(uid);
    uidRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.d("TAG", ""+dataSnapshot);

    username[0]=dataSnapshot.child("username").getValue(String.class);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            System.out.println("what"+databaseError);
        }
    });
    return username[0]; 
}

Upvotes: 0

Maytham Fahmi
Maytham Fahmi

Reputation: 33437

One way to go, with out having testing it, declare username as private variable in your class, like this:

private String username = null;

then use it another place in class

if (username != null){
    //TODO what ever with username
}

And in your inner class remove String and make your method as void

public void onDataChange(DataSnapshot dataSnapshot) {
    Log.d("TAG", ""+dataSnapshot);
    username = dataSnapshot.child("username").getValue(String.class);
}

Upvotes: 3

Abdul Waheed
Abdul Waheed

Reputation: 4678

Make you variable username as a global variable and inside annonymouse class give the value and return it

Upvotes: 0

Related Questions