我想检索来自Firestore的用户数据登录的电流,但它显示了我想显示数据的空白



我正在尝试从Google Firestore数据库中获取当前登录的用户我在用户的stackoverflow中看到了同样的问题,我使用了相同的方法,但显示了空白的用户详细信息。

请帮助我。

我较早使用querysnapshot,因为它给了所有用户。

图像描述在这里

数据库的图像是在此处输入图像描述

代码是:

 public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_profile);
    if(getSupportActionBar()!=null ){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
    DatabaseReference DBRef = Database.child("users");
    auth = FirebaseAuth.getInstance();
    UserId = auth.getCurrentUser().getUid();
        FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
    StorageReference mStorage = FirebaseStorage.getInstance().getReference();
    FirebaseStorage storage = FirebaseStorage.getInstance();
    photoview = (ImageView)findViewById(R.id.photoview);
    Photo = (ImageButton)findViewById(R.id.Photoedit);
    name = (TextView)findViewById(R.id.username);
    email = (TextView)findViewById(R.id.useremail);
    password = (TextView)findViewById(R.id.password1);
    phone = (TextView)findViewById(R.id.userPhone);
      mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
          @Override
          public void onSuccess(DocumentSnapshot documentSnapshot) {
                  String Name = documentSnapshot.getString("Name");
                  String Email = documentSnapshot.getString("Email");
                  String Password = documentSnapshot.getString("Password");
                  String Phone = documentSnapshot.getString("Phone Number");
                  name.setText(Name);
                  email.setText(Email);
                  password.setText(Password);
                  phone.setText(Phone);
          }
});

    Photo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}
private void selectImage() {
    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
    AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo"))
            {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            }
            else if (options[item].equals("Choose from Gallery"))
            {
                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, GALLERY_INTENT);

            }
            else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap photo = (Bitmap) extras.get("data");
        photoview.setImageBitmap(photo);

    } else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
        Uri selectedImage = data.getData();
        String[] filePath = {MediaStore.Images.Media.DATA};
        Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePath[0]);
        String picturePath = c.getString(columnIndex);
        c.close();
        Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
        Log.w("path of image ", picturePath + "");
        photoview.setImageBitmap(thumbnail);

    }
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == android.R.id.home) {
        Intent i = new Intent(UserProfile.this,category.class);
        startActivity(i);
        finish();
    }
    return super.onOptionsItemSelected(item);
}
}

我的数据库结构是

Ramiki(我的应用名称(所以这里是

Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).

很抱歉,我无法给出屏幕示威,因为堆栈溢出不允许10分。

和我在Firestore编写数据的代码是

public class LoginActivity extends AppCompatActivity  implements View.OnClickListener,
    GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    auth = FirebaseAuth.getInstance();
     mFirebaseFirestore = FirebaseFirestore.getInstance();
    FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
            .setPersistenceEnabled(true)
            .build();
    mFirebaseFirestore.setFirestoreSettings(settings);

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

        }
    };

    btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
    btnSignIn.setOnClickListener(this);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    // Customizing G+ button
    btnSignIn.setSize(SignInButton.SIZE_STANDARD);
    btnSignIn.setScopes(gso.getScopeArray());

    appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
    appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(LoginActivity.this, account.class);
            startActivity(i);
            finish();
        }
    });
    //if the user is already logged in we will directly start the category activity
    if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
        finish();
        startActivity(new Intent(this, category.class));
        finish();
        return;
    }

    findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String Name = textInputEditTextName.getText().toString().trim();
            String Email = textInputEditTextEmail.getText().toString().trim();
            String Password = textInputEditTextPassword.getText().toString().trim();
            String Phone_Number = textInputEditTextPhone.getText().toString().trim();
            String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
            progressBar.setVisibility(View.VISIBLE);


            // Create a new user with a first and last name
            Map<String, Object> user = new HashMap<>();
            user.put("Name", Name);
            user.put("Email", Email);
            user.put("Password", Password);
            user.put("Phone Number", Phone_Number);
            if (TextUtils.isEmpty(Name)) {
                textInputEditTextName.setError("Please enter name");
                textInputEditTextName.requestFocus();
                progressBar.setVisibility(View.GONE);
            }
            else if (TextUtils.isEmpty(Email)) {
                textInputEditTextEmail.setError("Please enter your email");
                textInputEditTextEmail.requestFocus();
                progressBar.setVisibility(View.GONE);
            }
            else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
                textInputEditTextEmail.setError("Email already exist");
                textInputEditTextEmail.requestFocus();
                progressBar.setVisibility(View.GONE);
            }

           else  if (TextUtils.isEmpty(Password)) {
                textInputEditTextPassword.setError("Enter a password");
                textInputEditTextPassword.requestFocus();
                progressBar.setVisibility(View.GONE);
            }
            else if(Password.length() < 7){
                textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
                textInputEditTextPassword.requestFocus();
                progressBar.setVisibility(View.GONE);
            }
            else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
                textInputEditTextPassword.setError("Password Doesn't Match");
                textInputEditTextPassword.requestFocus();
                progressBar.setVisibility(View.GONE);
            }
            else {

     // Add a new document with a generated ID
                mFirebaseFirestore.collection("users")
                        .add(user)
                        .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                            @Override
                            public void onSuccess(DocumentReference documentReference) {
                                registerUser();
                                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w(TAG, "Error adding document", e);
                            }
                        });

            }
        }

    });

    initViews();


}
@Override
public void onClick(View view) {
    int id = view.getId();
    switch (id) {
        case R.id.btn_sign_in:
            signIn();
            break;

    }
}
private void registerUser() {
    final String Name = textInputEditTextName.getText().toString().trim();
    final String Email = textInputEditTextEmail.getText().toString().trim();
    final String Password = textInputEditTextPassword.getText().toString().trim();
    final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
    final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
    //first we will do the validations
    if (TextUtils.isEmpty(Name)) {
        textInputEditTextName.setError("Please enter name");
        textInputEditTextName.requestFocus();
        return;
    }
    if (TextUtils.isEmpty(Email)) {
        textInputEditTextEmail.setError("Please enter your email");
        textInputEditTextEmail.requestFocus();
        return;
    }
    if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
        textInputEditTextEmail.setError("Email already exist");
        textInputEditTextEmail.requestFocus();
        return;
    }
    if (TextUtils.isEmpty(Password)) {
        textInputEditTextPassword.setError("Enter a password");
        textInputEditTextPassword.requestFocus();
        return;
   }
   if(Password.length() < 7 ) {
       textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
       textInputEditTextPassword.requestFocus();
       return;
   }
    if (TextUtils.isEmpty(ConfirmPassword)) {
        textInputEditTextPassword.setError("Password Doesn't Match");
        textInputEditTextPassword.requestFocus();
        return;
    }

    progressBar.setVisibility(View.VISIBLE);
    //create user
    auth.createUserWithEmailAndPassword(Email, Password)
            .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                    if (task.isSuccessful()){
                        sendEmailVerification();
                    }

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    else if (!task.isSuccessful()) {
                        Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
                    }
                }
            });

}
private void sendEmailVerification() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if(user != null){
        user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if(task.isSuccessful()){
                    Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
                    FirebaseAuth.getInstance().signOut();
                    startActivity(new Intent(LoginActivity.this, account.class));
                    finish();
                }
            }
        });
    }
}

@Override
protected void onResume() {
    super.onResume();
    progressBar.setVisibility(View.GONE);
}

private void initViews() {

    textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
    textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
    textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
    textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
    appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
    textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
    appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}

protected void onStart(){
    super.onStart();
    auth.addAuthStateListener(authListener);
}
private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            // ...
        }
    }
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
    auth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = auth.getCurrentUser();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
                    }
                    // ...
                }
            });
}

}

当您将用户添加为Map或使用document()方法的调用而无需传递参数时,将生成此唯一的ID SiQEIDaQJfUBqZBBt1eo

为了解决这个问题,有两种方法。一种是创建一个模型类(usermodel(,然后创建该类的对象,最后在用户身份验证后获取用户的UID,然后将对象添加到此类数据库中:

String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);

看,我已经将uid作为参数传递给document()方法。

第二种方法是将不参数传递给document()方法,而是将该键存储到这样的变量中:

String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);

编辑:

还有另一种方法,我建议您使用它。而不是使用此代码行:

 mFirebaseFirestore.collection("users")
                    .add(user)
                    .addOnSuccessListener(/* ... */)

使用以下代码行:

 mFirebaseFirestore.collection("users")
                    .document(uid)
                    .set(user)
                    .addOnSuccessListener(/* ... */)

删除旧数据,添加新的一个,您的问题将被解决。

最新更新