如何从Firebase Android

时间:2018-12-10 07:04:51

标签: android firebase firebase-realtime-database

我已经创建了个人资料页面,但是我无法检索作为根节点存储在用户下的用户详细信息。并且每个用户都存储在其userid节点下,但是我只检索该用户的个人资料图片,而未检索到其他详细信息-

这是我的DisplayProfile.java代码

public class DisplayProfile extends AppCompatActivity {
private static final String TAG = "DisplayProfile";
public static final String Firebase_Server_URL = "https://gakusei-go.firebaseio.com/";


private ImageView profilePic;
private TextView profileName, profilePhone, profileEmail;
private Button profileUpdate;
private FirebaseAuth firebaseAuth;
private FirebaseDatabase firebaseDatabase;
private FirebaseStorage firebaseStorage;
private String userID;
FirebaseUser user;
private FirebaseAuth.AuthStateListener mAuthListener;


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

    profileUpdate=(Button)findViewById(R.id.pbuttonSave);
    profilePic = findViewById(R.id.ivProfilePic);
    profileName = findViewById(R.id.tvProfileName);
    profilePhone = findViewById(R.id.tvProfilePhone);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseDatabase = FirebaseDatabase.getInstance();
    FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();

    System.out.println(userID);
    firebaseStorage = FirebaseStorage.getInstance();
    userID = firebaseAuth.getUid();
    System.out.println(userID);
    profileUpdate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            startActivity(new Intent(DisplayProfile.this, SecondActivity.class));

        }

    })
    mAuthListener = new FirebaseAuth.AuthStateListener() {
       @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                // Toast.makeText(getApplicationContext(),"Successfully signed in with: " + user.getEmail());
                Toast.makeText(getApplicationContext(), "Enter email address!" +user.getEmail(), Toast.LENGTH_SHORT).show();
            } else {
                                  Log.d(TAG, "onAuthStateChanged:signed_out");
                Toast.makeText(getApplicationContext(), "Successfuly signed out", Toast.LENGTH_SHORT).show();
            }
        }
    };
    StorageReference storageReference = firebaseStorage.getReference();
    storageReference.child("images").child(firebaseAuth.getUid()+ "." + "jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Picasso.get().load(uri).fit().centerCrop().into(profilePic);
        }
    });
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot Mainsnapshot) {

            for (DataSnapshot datasnapShot : Mainsnapshot.getChildren()) {

                Users userProfile = datasnapShot.getValue(Users.class);
                profileName.setText("Name: " + userProfile.getName());
                profilePhone.setText("Age: " + userProfile.getPhone());
                profileEmail.setText("Email: " + userProfile.getEmail());
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(DisplayProfile.this, databaseError.getCode(), Toast.LENGTH_SHORT).show();
        }
    });
  }
 }  

Users.java的代码在此处

    package com.example.deepak.myapplication;


   public class Users {
   public String imageUrl;
   public String imageName;
   public String uid;
   public String name;
   public String email;
   public String password;
   public String phone;

public Users() {
}


public Users(String uid, String name, String email, String password, String phone) {
    this.uid = uid;
    this.name = name;
    this.email = email;
    this.password = password;
    this.phone = phone;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

}

我的Display_activity在此处

     <?xml version="1.0" encoding="utf-8"?>
     <android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_image_upload"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical">

<ImageView
    android:id="@+id/ivProfilePic"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.238"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:srcCompat="@mipmap/ic_launcher" />

<Button
    android:id="@+id/pbuttonSave"
    android:layout_width="100dp"
    android:layout_height="50dp"
    android:layout_marginTop="40dp"
    android:layout_marginEnd="140dp"
    android:text="Edit"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tvProfilePhone" />


<TextView

    android:id="@+id/tvProfileName"
    android:layout_width="wrap_content"
    android:layout_height="36dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="208dp"
    android:textSize="28dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.401"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/ivProfilePic" />


<TextView
    android:id="@+id/tvProfilePhone"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:text="Phone: "
    android:textSize="28dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.378"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tvProfileName"
    app:layout_constraintVertical_bias="0.391" />


<TextView
    android:id="@+id/tvProfileEmail"
    android:layout_width="69dp"
    android:layout_height="41dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="160dp"
    android:text="Email"
    android:textSize="22dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.384"
    app:layout_constraintStart_toStartOf="parent" />
    </android.support.constraint.ConstraintLayout>

这是我的数据库结构

Database Structure

2 个答案:

答案 0 :(得分:0)

根据您的数据库,您拥有:

 users
     userId 
         name : user_name
         phone : user_phone 

然后您需要执行以下操作:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener()

在您的代码中,您拥有getReference("user"),然后编写了child("users"),这意味着您正在访问数据库中不存在的节点。


完整代码:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot mainSnapshot) {

            Users userProfile = mainSnapshot.getValue(Users.class);
            profileName.setText("Name: " + userProfile.getName());
            profilePhone.setText("Phone: " + userProfile.getPhone());
            profileEmail.setText("Email: " + userProfile.getEmail());
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});

答案 1 :(得分:0)

您的错误是在getReference("user")中,然后进一步引用了子users

但是您仍然设法获取个人资料图片,因为您是直接参考云存储来获取该图片的,您已经知道该个人资料图片被命名为gs://<bucket>/images/<uid>.jpg(而不使用imageURL您在RTDB中的用户数据中拥有的值)