如何从firebase数据库获取引用用户UID作为父级? #AskFirebase

时间:2016-12-29 23:34:48

标签: android firebase firebase-realtime-database firebase-authentication

This is my database in firebase

DatabaseReference myDatabase=FirebaseDatabase.getInstance().getReference();

private FirebaseAuth authData;
private EditText number;


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

    number= (EditText)findViewById(R.id.number);

    DatabaseReference lastdata=myDatabase.child("QExqazU73kTJllMFtsN0alwH6aq1").child("Schedule").child("Monday").child("Hour");

    lastdata.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            String text= dataSnapshot.getValue(String.class);
            number.setText(text);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

在这部分:

DatabaseReference lastdata=myDatabase.child("QExqazU73kTJllMFtsN0alwH6aq1").child("Schedule").child("Monday").child("Hour");

如果我写用户uid那样结果是真的。但是,我想获取属于已登录用户的用户uid。

如果我写

String user_id= authData.getCurrentUser().getUid();
DatabaseReference userid_database=myDatabase.child(user_id).child("Schedule").child("Monday").child("Hour");
像这样,程序关闭,不再运行。

2 个答案:

答案 0 :(得分:2)

如果没有看到程序关闭的异常,很难确定。但是,一个可能的问题是,当您尝试阅读他们的数据时,用户还没有登录,这会在尝试呼叫NullPointerException时导致getUid()

该问题的解决方案是等待用户通过身份验证:

 myAuth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            System.out.println("onAuthStateChanged:signed_in:" + user.getUid());
            String user_id= user.getUid();
            DatabaseReference userid_database=myDatabase.child(user_id).child("Schedule").child("Monday").child("Hour");
           ...
        }
    }
});

答案 1 :(得分:0)

将此信息放入您的登录活动

private DatabaseReference mDatabase;

mDatabase = FirebaseDatabase.getInstance().getReference();
AuthData authData = mDatabase.getAuth();
  if(authData!=null){
  //Get uid of logged in user
  uid = authData.getUid() ;
  Toast.makeText(getContext(), "-"+authData.getAuth().get("email"), Toast.LENGTH_SHORT).show();    
}