繁体   English   中英

如何在 Android 中使用 .setPhotoUri 从本地存储添加图片以更新 Firebase 用户的照片配置文件?

[英]How to add a picture from local storage to update Firebase user's photo profile using .setPhotoUri in Android?

我在 Firebase 中更新用户的照片配置文件时出错。 我想将用户的本地照片上传到 Firebase 用户的个人资料。 这是我的活动。

package naufal.com.tugasakhir;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.bumptech.glide.util.Util;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;

import java.text.ParseException;


public class EditProfile extends AppCompatActivity {

    private EditText mUsername;
    private Button mUpdateProfileBtn;
    private ImageButton mImageBtn;
    FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
    private static final int GALLERY_REQUEST = 1;
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    private Uri imageUri2;


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

        mUsername = (EditText) findViewById(R.id.userName);
        mUpdateProfileBtn = (Button) findViewById(R.id.updateProfileBtn);
        mImageBtn = (ImageButton) findViewById(R.id.imageField);
        String username = user.getDisplayName();
        mUsername.setText(username);

        mUpdateProfileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //updating user's profile data
                String nameUser = mUsername.getText().toString();
                UserProfileChangeRequest profileUpdate =  new UserProfileChangeRequest.Builder()
                        .setPhotoUri(Uri.parse(imageUri2))
                        .setDisplayName(nameUser)
                        .build();

                if(TextUtils.isEmpty(nameUser)){
                    mUsername.setError("Enter a username");
                }

                if(imageUri2 == null){
                    Toast.makeText(EditProfile.this, "Error updating image",
                            Toast.LENGTH_SHORT).show();
                }
                //if the field is not null, process continue to update profile
                else {
                    mUser.updateProfile(profileUpdate)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(Task<Void> task) {
                                    if (task.isSuccessful()) { //success on updating user profile
                                        Toast.makeText(EditProfile.this, "Update Profile Succedeed",
                                                Toast.LENGTH_SHORT).show();
                                        startActivity(new Intent(EditProfile.this, HomePage.class));
                                    } else { //failed on updating user profile
                                        Toast.makeText(EditProfile.this, "Update Profile Failed",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                }

            }
        });

        //setting image for user
        mImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, GALLERY_REQUEST);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){
            Uri imageUri = data.getData();
            mImageBtn.setImageURI(imageUri);
            imageUri2 = imageUri;
        } else {
            Toast.makeText(EditProfile.this, "Failed showing image",
                    Toast.LENGTH_SHORT).show();
        }
    }
}

这是我从 Firebase 获取用户个人资料的方式:

  String email = user.getEmail();
        String username = user.getDisplayName();
        Uri uriImage = user.getPhotoUrl();
        mUserName.setText(username);
        mUserStat.setText(email);
    mUriImageProfile.setImageURI(uriImage);

感谢您的回复。

您需要从您的设备获取此图像,将文件放入 firebase,然后将其用作链接

您可以检查我的 github 以查看它是否有效https://github.com/chrystianmelo/appmodule

代码

 **PROFILE_SERVICES** public void putFile(Bitmap bitmap){ FirebaseStorage storage = FirebaseStorage.getInstance(); final StorageReference storageRef = storage.getReference(); final StorageReference mountainsRef = storageRef.child("images/"+getUID()+".jpg"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] data = baos.toByteArray(); UploadTask uploadTask = mountainsRef.putBytes(data); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Log.i("chrys", "Img not set"); } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { mountainsRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onSuccess(Uri uri) { setProfilePic(uri); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Log.i("chrys", "Img set but whereeee"); // Handle any errors } }); } }); } @RequiresApi(api = Build.VERSION_CODES.KITKAT) public void setProfilePic(Uri uri){ UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder() .setPhotoUri(uri) .build(); user.updateProfile(profileUpdates); }
 **PROFILE_ACTIVITY** @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == PICK_IMAGE) { Bitmap bitmap; try { ProfileServices services = new ProfileServices(); bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Objects.requireNonNull(data.getData()))); services.putFile(bitmap); Log.i("chrys", "GET FROM LOCAL.: OK"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.i("chrys", "GET FROM LOCAL.: RUIM"); } } } } @SuppressLint("IntentReset") public void getImg(){ Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT); getIntent.setType("image/*"); @SuppressLint("IntentReset") Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); pickIntent.setType("image/*"); Intent chooserIntent = Intent.createChooser(getIntent, "Select Image"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent}); startActivityForResult(chooserIntent, PICK_IMAGE); } private static class DownLoadImageTask extends AsyncTask<String,Void,Bitmap> { @SuppressLint("StaticFieldLeak") ImageView imageView; DownLoadImageTask(ImageView imageView){ this.imageView = imageView; } /* doInBackground(Params... params) Override this method to perform a computation on a background thread. */ protected Bitmap doInBackground(String...urls){ String urlOfImage = urls[0]; Bitmap logo = null; try{ InputStream is = new URL(urlOfImage).openStream(); /* decodeStream(InputStream is) Decode an input stream into a bitmap. */ logo = BitmapFactory.decodeStream(is); }catch(Exception e){ // Catch the download exception e.printStackTrace(); } return logo; } /* onPostExecute(Result result) Runs on the UI thread after doInBackground(Params...). */ protected void onPostExecute(Bitmap result){ imageView.setImageBitmap(result); } } } <!-- begin snippet: js hide: false console: true babel: false -->

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM