用户个人资料无效。仅显示电子邮件

时间:2019-10-30 16:59:56

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

我试图在活动中显示用户的个人资料。但是,当我尝试执行此操作时,它仅显示电子邮件。名称,照片,电话号码未显示。

如何显示当前用户的所有字段?

我尝试了 getCurrentuser() 获取当前用户信息并在字段中进行设置。但这并没有显示所有字段。

SignUp.java


    private EditText signUpnameId, signUpemailId,signUppasswordId,signUpPhoneId;
    private Button signup_btn;
    private TextView signUpSignIn;
    private FirebaseAuth mAuth;
    private ProgressBar progressBar;
    private ImageView signUpimageView;

    private static final String IMAGE_DIRECTORY = "/demonuts";
    private int GALLERY = 1, CAMERA = 2;
    private DatabaseReference mDatabase;

    private Uri imageUri;
    private String imageurl;

    private static final int IMAGE_REQUEST = 1;

    private StorageReference storageReference,imagename;
    private StorageTask uploadTask;


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

        this.setTitle("Sign Up Here");


        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        progressBar =  findViewById(R.id.progressbarId);
        signUpnameId =  findViewById(R.id.signUpnameId);
        signUpemailId =  findViewById(R.id.signUpemailId);
        signup_btn =  findViewById(R.id.signup_btn);
        signUpSignIn =  findViewById(R.id.signUpSignIn);
        signUppasswordId =  findViewById(R.id.signUppasswordId);
        signUpimageView =findViewById(R.id.signUpImageId);
        signUpPhoneId = findViewById(R.id.signUpphoneId);

        mDatabase = FirebaseDatabase.getInstance().getReference("Users");
        storageReference = FirebaseStorage.getInstance().getReference("usersImage");


        signUpSignIn.setOnClickListener(this);
        signup_btn.setOnClickListener(this);
        signUpimageView.setOnClickListener(this);




    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.signup_btn:
                userRegister();
                break;

            case R.id.signUpSignIn:
                Intent intent = new Intent(getApplicationContext(),LogIn.class);
                startActivity(intent);
                break;

            case R.id.signUpImageId:
                if(uploadTask != null && uploadTask.isInProgress())
                {
                    Toast.makeText(getApplicationContext(),"Upload in process.",Toast.LENGTH_SHORT).show();
                }else {
                    showPictureDialog();
                }

        }

    }


    private void showPictureDialog(){
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "Select photo from gallery" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallary();
                                break;

                        }
                    }
                });
        pictureDialog.show();
    }


    public void choosePhotoFromGallary() {
        Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(galleryIntent, GALLERY);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            return;
        }
        if (requestCode == GALLERY && data != null && data.getData() != null ) {
            imageUri = data.getData();
            try {
                Picasso.get().load(imageUri).into(signUpimageView);
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private String getFileExtension(Uri uri){
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getExtensionFromMimeType(contentResolver.getType(uri));
    }

    private void userRegister() {

        final String name =  signUpnameId.getText().toString();
        final String email =  signUpemailId.getText().toString().trim();
        final String password = signUppasswordId.getText().toString().trim();
        final String phoneNum = signUpPhoneId.getText().toString();



        if(email.isEmpty())
        {
            signUpemailId.setError("Enter an email address");
            signUpemailId.requestFocus();
            return;
        }

        if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches())
        {
            signUpemailId.setError("Enter a valid email address");
            signUpemailId.requestFocus();
            return;
        }

        //checking the validity of the password
        if(password.isEmpty())
        {
            signUppasswordId.setError("Enter a password");
            signUppasswordId.requestFocus();
            return;
        }

        if(password.length() < 6)
        {
            signUppasswordId.setError("Password is too short. Password Should be more than 6");
            signUppasswordId.requestFocus();
            return;
        }

        //checking the validity of the password
        if(name.isEmpty())
        {
            signUpnameId.setError("Enter a Name");
            signUpnameId.requestFocus();
            return;
        }
        if(imageUri == null)
        {
            signUpSignIn.setError("Please select an image first");

        }


        progressBar.setVisibility(View.VISIBLE);

        mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                progressBar.setVisibility(View.GONE);
                if(task.isSuccessful())
                {
                    mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {


                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if(task.isSuccessful())
                            {
                                final StorageReference Imagename = storageReference.child("image"+imageUri.getLastPathSegment());
                                imageurl = imageUri.toString();
                                Imagename.putFile(imageUri)
                                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                            @Override
                                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                                Toast.makeText(getApplicationContext(),"Place added Done!",Toast.LENGTH_SHORT).show();
                                                Task<Uri> uriTask = taskSnapshot.getMetadata().getReference().getDownloadUrl();
                                                while(!uriTask.isSuccessful());
                                                Uri downloadUrl = uriTask.getResult();
                                                UserInfo userInfo = new UserInfo(name,email,phoneNum,downloadUrl.toString());
                                                String uploadId = mDatabase.push().getKey();
                                                mDatabase.child(uploadId).setValue(userInfo);

                                            }
                                        })
                                        .addOnFailureListener(new OnFailureListener() {
                                            @Override
                                            public void onFailure(@NonNull Exception exception) {
                                                // Handle unsuccessful uploads
                                                // ...
                                            }
                                        });

                            }
                            else
                            {
                                Toast.makeText(getApplicationContext(),"Error: "+task.getException().getMessage(),Toast.LENGTH_SHORT).show();

                            }
                        }
                    });

                }
                else
                {
                    if(task.getException() instanceof FirebaseAuthUserCollisionException)
                    {
                        Toast.makeText(getApplicationContext(),"Already registered",Toast.LENGTH_SHORT).show();

                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),"Eroor: "+ task.getException(),Toast.LENGTH_SHORT).show();

                    }
                }
            }
        });

    }

Profile.Java

private ImageView profileImageview;
   private TextView profilenameview,profileemailview, profilephoneview;
   private Button profilesignoutbtn;
   private FirebaseUser firebaseUser;
   private FirebaseAuth mAuth;
   private FirebaseDatabase firebaseDatabase;

   private ProgressBar progressBar;

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

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
        final FirebaseUser user = mAuth.getCurrentUser();
        firebaseDatabase = FirebaseDatabase.getInstance();
        profileImageview = findViewById(R.id.profileImageView);
        profileemailview = findViewById(R.id.profileemailview);
        profilenameview = findViewById(R.id.profilenameview);
        profilephoneview = findViewById(R.id.profilephoneview);
        progressBar = findViewById(R.id.progressbarproId);
        profilesignoutbtn = findViewById(R.id.profilesignout_btn);
        profilesignoutbtn.setOnClickListener(this);

        // Initialize Firebase Auth
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Image");
        mAuth = FirebaseAuth.getInstance();
        String userKey = user.getUid();


        databaseReference.child("Profile");
        databaseReference.child(userKey);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String userName = dataSnapshot.child("users").getValue(String.class);
                profilenameview.setText(user.getDisplayName());
                profileemailview.setText(user.getEmail());
                Picasso.get().load(user.getPhotoUrl()).into(profileImageview);
            }

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

    }

UserInfo.java


public class UserInfo{

    String name,email,phoneNum,imageurl;

    public UserInfo(String name, String email, String phoneNum, String imageurl) {
        this.name = name;
        this.email = email;
        this.phoneNum = phoneNum;
        this.imageurl = imageurl;
    }

    public UserInfo(String name, String email, String phoneNum, Uri uri) {
    }

    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 getPhoneNum() {
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }

    public String getImageurl() {
        return imageurl;
    }

    public void setImageurl(String imageurl) {
        this.imageurl = imageurl;
    }
}

Android Studio显示 sendEmailVerification()  可能会产生NullPointerException。除了 getReference()  和 getDownloadUrl()  也可能产生NullPOinterException。如何解决所有问题并正确获得预期的输出? Here is a screenshot of profile.

1 个答案:

答案 0 :(得分:0)

您实际上并没有定义用户名, 在Firebase身份验证

的onCompleteListener方法中使用此方法
new UserProfileChangeRequest.Builder()
                 .setDisplayName(nameUser)
                 .build();