如何从当前登录的用户 Firebase、Android 中检索值

我无法从数据快照中检索任何值。我尝试了多种方法和技巧,但它给出了一个空值。

https://img4.mukewang.com/650178820001e10504930291.jpg

我的数据库的图像如上。请参阅下面的代码,尝试记录一个值,一切似乎都正确但不起作用。


email = view.findViewById(R.id.email);

editTextfragmentF = view.findViewById(R.id.editText_firstname);

editTextfragmentL = view.findViewById(R.id.editText_lastname);


    FirebaseAuth mAuth = FirebaseAuth.getInstance();

    String UserID = mAuth.getCurrentUser().getUid();


    FirebaseDatabase database = FirebaseDatabase.getInstance();

    database.getReference().child("Users").child(UserID).addChildEventListener(new ChildEventListener() {

        @Override

        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            if (mAuth.getCurrentUser() != null) {

                email.setText(mAuth.getCurrentUser().getEmail());


                //Gets current users first name

                String FN = String.valueOf(dataSnapshot.child("firstName").getValue());

                Log.i("First Name", FN);


                /*String LN = dataSnapshot.child("lastName").getValue().toString();

                Log.i("Last Name", LN);*/

                /*editTextfragmentF.setText(FN);

                editTextfragmentF.requestFocus();*/


                /*editTextfragmentL.setText(LN);

                editTextfragmentL.requestFocus();*/

            }

        }

结果:

https://img1.mukewang.com/6501788e0001a16605740048.jpg

Smart猫小萌
浏览 80回答 2
2回答

浮云间

你需要改变database.getReference().child("Users").child(UserID).addChildEventListener和&nbsp; &nbsp; database.getReference().child("Users").child(UserID).addValueEventListener(new ValueEventListener() {&nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; public void onDataChange(DataSnapshot dataSnapshot) {&nbsp; &nbsp; &nbsp; &nbsp; email.setText(dataSnapshot.child("email").getValue(String.class));&nbsp; &nbsp; &nbsp; &nbsp; String FN = dataSnapshot.child("firstName").getValue(String.class);&nbsp; &nbsp; &nbsp; &nbsp; Log.i("First Name", FN);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; public void onCancelled(DatabaseError databaseError) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("The read failed: " + databaseError.getCode());&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });确保您已授予互联网访问权限AndroidManifest.xml<manifest xlmns:android...>&nbsp;...&nbsp;<uses-permission android:name="android.permission.INTERNET" />&nbsp;<application ...</manifest>

慕神8447489

getValue() 接受要返回的对象的类型。在您的情况下,您正在获取一个字符串值,因此只需将 String.class 传递到方法中,然后将其保存到 String 变量中。String&nbsp;firstname=dataSnapshot.getValue(String.class); Log.i("First&nbsp;Name",&nbsp;firstname);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java