Nico Aramy
Nico Aramy

Reputation: 55

How to update profile image to firebase after select picture and crop it?

How can I update my current user profile picture into firebase after I select an image and crop it?

Here is my code:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == RESULT_OK){
        Uri imageUri = CropImage.getPickImageResultUri(getActivity(),data);
        cropRequest(imageUri);

    }
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK){
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), result.getUri());
                imgUserProfile.setImageBitmap(bitmap);

                final ProgressDialog pd = new ProgressDialog(getContext());
                pd.setMessage("Please wait ");
                pd.show();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

How do I continue from there? Any suggestions?

Upvotes: 1

Views: 1591

Answers (2)

Stradtdog
Stradtdog

Reputation: 1550

This is the option that worked for me. First, make sure you have your firebase correctly set up with Real time database and storage. Then in your build gradle;

implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.squareup.picasso:picasso:2.5.2'

In the activity that updates your profile image, create a reference to your image and a Firebase Storagebase reference. Also add these four extra lines:

private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private CircleImageView ProfileImage;
private StorageReference UserProfileImageRef;
String currentUserID;
final static int Gallery_Pick = 1;

In your onCreate method, include these lines of code:

mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersRef= FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");`

Also, add this to your on create method. This allows the user to update their picture:

UsersRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            if(dataSnapshot.exists())
            {
                if (dataSnapshot.hasChild("profileimage"))
                {
                    String image = dataSnapshot.child("profileimage").getValue().toString();
                    Picasso.with(SetupActivity.this).load(image).placeholder(R.drawable.profile).into(ProfileImage);
                }
                else
                {
                    Toast.makeText(SetupActivity.this, "Please select profile image first.", Toast.LENGTH_SHORT).show();
                }
            }
        }`

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

This will allow the use to select a different profile image from his device. It will also allow the user to crop the image to fit the screen.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        Uri ImageUri = data.getData();

        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1, 1)
                .start(this);
    }

    if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);

        if(resultCode == RESULT_OK)
        {
            loadingBar.setTitle("Profile Image");
            loadingBar.setMessage("Please wait, while we updating your profile image...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            Uri resultUri = result.getUri();

            StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");

            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull final Task<UploadTask.TaskSnapshot> task)
                {
                    if(task.isSuccessful())
                    {
                        Toast.makeText(SetupActivity.this, "Profile Image stored successfully to Firebase storage...", Toast.LENGTH_SHORT).show();

                        final String downloadUrl = task.getResult().getDownloadUrl().toString();

                        UsersRef.child("profileimage").setValue(downloadUrl)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task)
                                    {
                                        if(task.isSuccessful())
                                        {
                                            Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
                                            startActivity(selfIntent);

                                            Toast.makeText(SetupActivity.this, "Profile Image stored to Firebase Database Successfully...", Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }
                                        else
                                        {
                                            String message = task.getException().getMessage();
                                            Toast.makeText(SetupActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }
                                    }
                                });
                    }
                }
            });
        }
        else
        {
            Toast.makeText(this, "Error Occured: Image can not be cropped. Try Again.", Toast.LENGTH_SHORT).show();
            loadingBar.dismiss();
        }
    }
}                                         

If your looking for someone who explains this concept better than I do, I suggest following this link. The creator makes a fully functional android social media app with all of these features.

https://www.youtube.com/playlist?list=PLxefhmF0pcPnTQ2oyMffo6QbWtztXu1W_

Upvotes: 1

Gaurav Mall
Gaurav Mall

Reputation: 2412

There are many options:

  1. One of the most useful ones I would use would be to upload the picture to Firebase Storage. It's really easy to upload it, and whenever your user signs in again you could download the file to local storage for daily usage.
  2. Another option(this is a bit clunky) might be to store the pixel array of the bitmap in a firebase node. It is blazingly fast and you can store it in your firebase database, but also in your shared preferences. By using an additional compression function you could even enhance the function.

I would recommend, however, using firebase storage as it is the one and only secure option. So go for it. For firebase storage take a look at this link it's the documentation(pretty easy to follow):

https://firebase.google.com/docs/storage/android/upload-files

And also here: https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934

Upvotes: 2

Related Questions