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

时间:2016-10-05 12:47:54

标签: android firebase firebase-authentication

在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);

感谢您的回复。

1 个答案:

答案 0 :(得分:1)

您需要从设备中获取此图像,将文件放入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 -->