【问题标题】:Upload profile image for a user Firebase上传用户 Firebase 的个人资料图片
【发布时间】:2022-02-14 00:01:48
【问题描述】:

我正在尝试将图像添加到 android 实时数据库 (firebase) 中的用户信息中。我已将图像上传到 firebase 存储,但我如何才能在数据库中为该用户添加图像?

代码如下:

//inside onCreate() method

img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i=new Intent(Intent.ACTION_PICK);
            i.setType("image/*");
            startActivityForResult(i,request_code);
        }
    });

我在这里单击图像视图,因此我可以更改它并从图库中获取图像。

这里我对用户进行身份验证并将数据发送到数据库:

 auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(StudentSignUpActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Toast.makeText(getApplicationContext(), "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                            progressBar.setVisibility(View.GONE);
                            // 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.
                            if (!task.isSuccessful()) {
                                Toast.makeText(getApplicationContext(), "Authentication failed." + task.getException(),
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                startActivity(new Intent(StudentSignUpActivity.this, HomeActivity.class));
                                finish();
                            }
                        }
                    });

mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
            DatabaseReference newStudent=mDatabase.push();
            newStudent.child("email").setValue(email);
            newStudent.child("password").setValue(password);
            newStudent.child("name").setValue(name);
            newStudent.child("date").setValue(dates);
            newStudent.child("phone").setValue(number);
            newStudent.child("uid").setValue(mCurrentUser.getUid());


//outside of onCreate()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==request_code&&resultCode==RESULT_OK){
        Uri uri=data.getData();
        StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

            }
        });
    }
}

在上面的代码中,我已将图像上传到 Firebase 存储。现在我将如何将该图像添加为特定用户的子图像。

我想我需要这样做:

 newStudent.child("image").setValue(uri_here);

但我无法弄清楚如何获取图像的 uri 以及如何在 setValue() 中添加该 uri,因为它是在另一种方法中。

【问题讨论】:

    标签: android image firebase firebase-realtime-database


    【解决方案1】:

    可以在成功监听器中使用getDownloadUrl()方法访问下载地址:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==request_code&&resultCode==RESULT_OK){
            Uri uri=data.getData();
            StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    newStudent.child("image").setValue(downloadUrl);
                }
            });
        }
    }
    

    顺便说一句,我建议不要使用push(),而是使用uid 作为键来存储用户的数据。这将使您的数据更容易找到。

    private DatabaseReference newStudent;
    
    mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
                newStudent=mDatabase.child(mCurrentUser.getUid());
                newStudent.child("email").setValue(email);
                // etc
    

    【讨论】:

    • 实际上newStudent=mDatabase.child(mCurrentUser.getUid()) 不起作用,它返回空点异常,因为还没有用户登录。以上代码用于注册
    • 您可以从 firebase 获取图像 uri。但是 uri 附带了令牌。您可以将该 uri 更新为用户配置文件。但问题是,如果令牌过期了怎么办?当您尝试获取用户个人资料网址时,可能会出错。
    • 如果用户更改配置文件怎么办? url 发生变化,因此数据库中使用先前 url 的位置将显示旧图像。如何克服?
    【解决方案2】:

    只是为了更新,因为我花了一些时间找到这个答案,getDownloadUrl() 不再是taskSnapshot 的功能。因此,为了从 Firebase Storage 获取图像 URL,您需要添加一个监听器 taskSnapshot.getMetadata().getReference().getDownloadUrl()

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==request_code&&resultCode==RESULT_OK){
            Uri uri=data.getData();
            StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    taskSnapshot.getMetadata().getReference().getDownloadUrl()
                        .addOnSuccessListener(new OnSuccessListener<Uri>() {
    
                        @Override
                        public void onSuccess(Uri uri) {
                            newStudent.child("image").setValue(uri);
    
                        }
                    });
                }
            });
        }
    }
    

    现在可以安全地将 uri 用于您想要的任何东西

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2017-05-04
      • 2015-05-22
      • 2014-10-05
      • 2020-01-10
      • 2014-04-14
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      相关资源
      最近更新 更多