无法在静态方法

时间:2018-02-02 19:17:03

标签: android firebase

我需要更新静态变量。 我从Firebase获取值,但似乎在addListenerForSingleValueEvent之外,静态变量未更新。哪里错了?

Flom logcat:

02-02 18:16:47.146 8329-8329/xxx E/query_result: null <-- wrong
02-02 18:16:47.675 8329-8329/xxx E/query: Dogee <-- correct

代码:

class FirebaseUtil {

    public static String nameOfCurrentUser;

// other code . . . 

   public static Author getAuthor() {

        // Is the current user running the app registered?
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null) return null;
        DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

        // 20180202 Add the listener on db /users/$currentUID
        mDatabase.child("users").child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                // Getting the child full_name of the user (mDatabase.child("users").child(user.getUid()))
                nameOfCurrentUser = (String)dataSnapshot.child("full_name").getValue();
                Log.e("query",nameOfCurrentUser);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w("DB read error", "loadPost:onCancelled", databaseError.toException());
                // ...
            }
        });

        if (nameOfCurrentUser == null) {
        Log.e("query_result","null");

正如你所看到的,一旦我不在方法中,变量nameOfCurrentUser在方法内是!= null,在外面是null。

0 个答案:

没有答案