Firebase - 在片段中使用addValueEventListener不起作用

时间:2018-05-08 13:17:11

标签: java android firebase firebase-realtime-database fragment

我正在努力解决这个问题差不多一个星期,现在尝试一切,但我无法帮助自己...... 该片段应该只从实时数据库中的节点加载用户名。代码在普通的Activity中完美运行,但它在这个片段中不起作用.. 我认为听众没有正常工作,但我不知道为什么:/ 我希望在我失去理智之前有人可以帮助我......

提前致谢!!

Firebase中的实时数据库如下所示:

DatabaseName
    Users
        UID(Unique User ID)
            fullname
            username
######

Fragment类,只是conCreateView()

private FirebaseDatabase mDatabase;
private FirebaseAuth mAuth;
private String currentUserID;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootview = inflater.inflate(R.layout.fragment_profile, container, false);

    username_et = (EditText) rootview.findViewById(R.id.profile_username);
    email_et = (EditText) rootview.findViewById(R.id.profile_email);
    change_btn = (Button) rootview.findViewById(R.id.profile_change_btn);

    mAuth = FirebaseAuth.getInstance();
    mDatabase = FirebaseDatabase.getInstance();

    DatabaseReference mRef = mDatabase.getReference("Users").child(mAuth.getCurrentUser().getUid());

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.e("Error","onDataChange fired!");
            String username = dataSnapshot.child("username").getValue().toString();
            username_et.setText(username);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });



    final String email = mAuth.getCurrentUser().getEmail();
    email_et.setText(email);

    return rootview;
}

1 个答案:

答案 0 :(得分:0)

您应该使用onViewCreated方法而不是onCreateView执行所有功能。所以在onViewCreated

中执行setText或其他方法

所以在你的情况下,只需将这行代码从onCreateView移到onViewCreated方法 -

DatabaseReference mRef = mDatabase.getReference("Users").child(mAuth.getCurrentUser().getUid());

mRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Log.e("Error","onDataChange fired!");
        String username = dataSnapshot.child("username").getValue().toString();
        username_et.setText(username);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});



final String email = mAuth.getCurrentUser().getEmail();
email_et.setText(email);