java - 将 userId 与 Firebase 中的唯一照片连接起来

标签 java firebase

我有一个可以创建用户的应用程序,它工作得很好,我很高兴!

简单来说,以下是将用户添加到 Firebase 数据库的方法:

    public void addUserInfoToDatabase(){
    String user_id = mAuth.getCurrentUser().getUid();
    final DatabaseReference the_user_database = FirebaseDatabase.getInstance().getReference().child("UserRegistraion").child(user_id);


    Map userAttributes = new HashMap();
    userAttributes.put("user_id", user_id);
    userAttributes.put("username", userName);
    userAttributes.put("name", name);
    userAttributes.put("e-mail", email);

    the_user_database.setValue(userAttributes);
    if (mRegistrationListener != null)
        mRegistrationListener.onRegistrationComplete(true); // Assumes success

}

这是用户注册后表格的外观:

User table

我现在想做的是,我希望能够添加属于每个用户的个人资料图片:例如个人资料图片、家庭图片等。

问题是:如何在 Firebase 中执行此操作?我并不是要求任何人为我做这件事,只是为了给我一个很好的提示或提供如何做到这一点的指南/视频。

谢谢。

最佳答案

我通常创建一个单独的 Activity 来设置个人资料照片。也许不是调用 onRegistrationComplete 而是在 setValue(userAttributes) 之后调用 onCompleteListener,如下所示:

the_user_database.setValue(userAttributes).addOnCompleteListener(new OnCompleteListener...){
Intent intent = new Intent(context, AddProfileActivity.class);
startActivity(intent);

在下一个 Activity 中,它可能是一个带有按钮和 ImageView 的简单 XML 布局。

此代码可以打开您的图库,选择一个图像,并将其放置在 onActivityResult 方法中的 imageview 中:

private void selectPhotoFromGallery(){
        Log.d(TAG, "selectPhotoFromGallery: started");
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, GALLERY_PICK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_PICK){
            if (resultCode == RESULT_OK && data != null){
                contentUri = data.getData();
                try{
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentUri);
                    profile_photo.setImageBitmap(bitmap);
                }catch (IOException e){
                    Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    }

然后,您需要一种方法将图像上传到 FirebaseStorage 并捕获 downloadUrl 以添加到所需的节点。在这种情况下,因为您要添加到现有节点,所以在添加个人资料照片时调用 updateChildren() 。我使用这样的方法:

private void uploadProfileImage(){
        Log.d(TAG, "uploadProfileImage: uploading image....");
        if (contentUri != null){
            //from gallery
            final StorageReference reference = FirebaseStorage.getInstance().getReference().child(currentUserID).child("profile_photo");
            reference.putFile(contentUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            String profilePhotoUri = uri.toString();
                            DatabaseReference publicUserReference = FirebaseDatabase.getInstance().getReference().child("public_user")
                                    .child(currentUserID);
                            HashMap hashMap = new HashMap();
                            hashMap.put("profile_photo", profilePhotoUri);
                            publicUserReference.updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() {
                                @Override
                                public void onComplete(@NonNull Task task) {
                                    if (task.isSuccessful()){
                                        Intent intent = new Intent(mContext, CompleteProfileActivity.class);
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                        finish();
                                    }
                                }
                            });

                        }
                    });
                }
            });
        }
    }

显然,您需要根据您的特定需求进行调整。您真正想做的是将图像保存到存储并获取存储图像的 http://... 字符串位置,然后将该信息插入到与您之前提供的信息相同的位置。

我希望这是一个有用的提示。 https://www.youtube.com/watch?v=mPOhnTnLcSY这是有关将图像上传到 Firebase 存储的视频的链接,您可以根据需要了解更多信息。祝你好运!

关于java - 将 userId 与 Firebase 中的唯一照片连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59987827/

相关文章:

java - 是否可以做一个动态 LLVM 汇编器(来自 Java 等高级语言)?

java - 如何在Java中对同一个对象进行多次引用

authentication - Firebase 短信验证/身份验证

java - Firestore 回收器适配器未获取文档名称

java - 如何在 log4j2 中创建自定义 Appender?

java.lang.NoSuchMethodError : org. apache.log4j.Logger 错误

java - 存储文本文档中的字符串并将其打印到屏幕上

java.lang.IllegalStateException 在 android.app.ContextImpl.startServiceCommon

xcode - 如何将 tensorflow-lite 模型转换为 coreml .mlmodel

java - 如何在 Android 中验证 IAP?