How do I upload image to firebase and retrieve it using picasso

Discussion in 'Java' started by java264, Apr 28, 2019.

  1. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    I am following a tutorial that shows you how to create an app like WhatsApp but I am having a very very hard time with one problem.

    When the user goes to their SettingsActivity they see their default image, name and status. When I click on the default image, I go to the gallery on my phone and select the image I want to use. When I select it I crop out the image and then I hit the word crop in the top right hand corner. I get the message that it's cropping the image and then it says the image upload was successful.

    When I look in my Firebase Database, this is what I see the image is stored as
    "com.google.android.gms.tasks.zzu@44d8fb0"

    But even though it's in the Database it's still showing me the default profile pic. When I click update and then go back to the SettingsActivity there is no picture where the profile pic is suppose to be. Not even the default image. I tried debugging this and changing my code around but nothing help me. Can anyone help me ?

    SettingsActivity :

    <pre> private Button UpdateAccountSettings;
    private EditText userName, userStatus;
    private CircleImageView userProfileImage;

    private String currentUserID;
    private FirebaseAuth mAuth;
    private DatabaseReference RootRef;

    private static final int GalleryPick = 1;
    private StorageReference UserProfileImagesRef;
    private ProgressDialog loadingBar;

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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    RootRef = FirebaseDatabase.getInstance().getReference();
    UserProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile Images");

    InitializeFields();

    userName.setVisibility(View.INVISIBLE);

    UpdateAccountSettings.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    UpdateSettings();
    }
    });

    RetrieveUserInfo();

    userProfileImage.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, GalleryPick);

    }
    });
    }

    private void InitializeFields() {

    userName = (EditText) findViewById(R.id.set_user_name);
    userStatus = (EditText) findViewById(R.id.set_profile_status);
    userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
    loadingBar = new ProgressDialog(this);
    UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
    }

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

    if(requestCode == GalleryPick && 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("Set Profile Image");
    loadingBar.setMessage("Please wait your profile image is updating...");
    loadingBar.setCanceledOnTouchOutside(false);
    loadingBar.show();

    final Uri resultUri = result.getUri();

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

    filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

    if(task.isSuccessful())
    {

    Toast.makeText(SettingsActivity.this, "Profile pic upload successful", Toast.LENGTH_SHORT).show();

    String downloadUrl = task.getResult().getMetadata().getReference().getDownloadUrl().toString();

    RootRef.child("Users").child(currentUserID).child("image")
    .setValue(downloadUrl)
    .addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {

    if(task.isSuccessful()){

    Toast.makeText(SettingsActivity.this, "Image is saved", Toast.LENGTH_SHORT).show();
    loadingBar.dismiss();
    } else {

    String message = task.getException().toString();
    Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
    loadingBar.dismiss();
    }
    }
    });

    } else {
    String message = task.getException().toString();
    Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
    loadingBar.dismiss();

    }
    }
    });
    }
    }
    }

    private void UpdateSettings() {

    String setUserName = userName.getText().toString();
    String setStatus = userStatus.getText().toString();

    if(TextUtils.isEmpty(setUserName)){

    Toast.makeText(this, "Please enter your user name...", Toast.LENGTH_SHORT).show();
    }
    if(TextUtils.isEmpty(setStatus)){

    Toast.makeText(this, "Please write your status...", Toast.LENGTH_SHORT).show();
    }
    else {

    HashMap<String, Object> profileMap = new HashMap<>();
    profileMap.put("uid", currentUserID);
    profileMap.put("name", setUserName);
    profileMap.put("status", setStatus);

    RootRef.child("Users").child(currentUserID).updateChildren(profileMap)
    .addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {

    if(task.isSuccessful()){

    SendUserToMainActivity();
    Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();

    } else{

    String message = task.getException().toString();
    Toast.makeText(SettingsActivity.this, "Error:", Toast.LENGTH_SHORT).show();
    }

    }
    });
    }
    }

    private void RetrieveUserInfo() {

    RootRef.child("Users").child(currentUserID)
    .addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

    if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("image"))))
    {

    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
    String retrieveStatus = dataSnapshot.child("status").getValue().toString();
    String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

    userName.setText(retrieveUserName);
    userStatus.setText(retrieveStatus);
    Picasso.get().load(retrieveProfileImage).into(userProfileImage);

    }

    else if ((dataSnapshot.exists()) && (dataSnapshot.hasChild("name")))
    {

    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
    String retrieveStatus = dataSnapshot.child("status").getValue().toString();

    userName.setText(retrieveUserName);
    userStatus.setText(retrieveStatus);
    }

    else {

    userName.setVisibility(View.VISIBLE);
    Toast.makeText(SettingsActivity.this, "Update your info", Toast.LENGTH_SHORT).show();

    }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
    });
    }

    private void SendUserToMainActivity() {

    Intent mainIntent = new Intent(SettingsActivity.this, MainActivity.class);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(mainIntent);
    finish();
    }
     
    java264, Apr 28, 2019
    #1
    1. Advertisements

  2. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    The reason is because the image url("com.google.android.gms.tasks.zzu@44d8fb0") is not a valid url.
    Can you try display retrieveProfileImage using Toast? What value you get ?
     
    John Joe, Apr 29, 2019
    #2
    1. Advertisements

  3. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    Honestly I don't remember how to do that
     
    java264, Apr 29, 2019
    #3
  4. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    Here the code for Toast
    Code (Text):
    Toast.makeText(getApplication(),retrieveProfileImage,Toast.LENGTH_SHORT).show()
     
    John Joe, Apr 29, 2019
    #4
  5. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0

    I did it like this

    String retrieveUserName = dataSnapshot.child("name").getValue().toString();
    String retrieveStatus = dataSnapshot.child("status").getValue().toString();
    String retrieveProfileImage = dataSnapshot.child("image").getValue().toString();

    userName.setText(retrieveUserName);
    userStatus.setText(retrieveStatus);
    Toast.makeText(SettingsActivity.this,retrieveProfileImage,Toast.LENGTH_SHORT).show();

    and this is what I see

    "com.google.firebase.storage.UploadTask$TaskSnapshot@e5e4816"

    and after that the app crashed
     
    Last edited: Apr 29, 2019
    java264, Apr 29, 2019
    #5
  6. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    What is the crash report ?
     
    John Joe, Apr 29, 2019
    #6
  7. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    Well now it's not crashing anymore but when I click to change the image the default pic stays the same
     
    java264, Apr 29, 2019
    #7
  8. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    Send whole project to me and show me your firebase structure if you don't mind.
     
    John Joe, Apr 29, 2019
    #8
  9. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    I tried to zip it up but I got an error message saying it's too large
     
    java264, Apr 29, 2019
    #9
  10. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    post to github
     
    John Joe, Apr 29, 2019
    #10
  11. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    It's still too large I can't upload anything over 25mb
     
    java264, Apr 29, 2019
    #11
  12. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    Can I email it to you ?
     
    java264, Apr 29, 2019
    #12
  13. java264

    java264

    Joined:
    Apr 28, 2019
    Messages:
    8
    Likes Received:
    0
    With the email I can just zip and send
     
    java264, Apr 29, 2019
    #13
  14. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    sure
     
    John Joe, Apr 29, 2019
    #14
  15. java264

    John Joe

    Joined:
    Apr 25, 2017
    Messages:
    120
    Likes Received:
    14
    Location:
    Malaysia
    I will suggest you to upload image and text by using below method.

    In UpdateSettings function, create an Item class.

    Code (Java):
     private void UpdateSettings() {

            String setUserName = userName.getText().toString();
            String setStatus = userStatus.getText().toString();

            if (TextUtils.isEmpty(setUserName)) {
                Toast.makeText(this, "Please enter your user name...", Toast.LENGTH_SHORT).show();
            }
            if (TextUtils.isEmpty(setStatus)) {
                Toast.makeText(this, "Please write your status...", Toast.LENGTH_SHORT).show();
            } else {
                Item item =new Item();
                if(resultUri!=null) {
                   item = new Item(resultUri.toString(), setUserName, setStatus, currentUserID);
                }else{
                     item = new Item(retrieveProfileImage, setUserName, setStatus, currentUserID);
                }
                RootRef.setValue(item).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()) {
                            SendUserToMainActivity();
                            Toast.makeText(SettingsActivity.this, "Profile Updated Successfully", Toast.LENGTH_SHORT).show();
                        } else {
                            String message = task.getException().toString();
                            Toast.makeText(SettingsActivity.this, "Error:", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    Noted that I am passing the Uri to firebase. So when you want to retrieve, you will get a valid url.

    Item
    Code (Java):
    package com.example.chatterbox;

    public class Item {

        String  image;
        String name;

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        String status;
        String uid;


        public Item(String resultUri, String setUserName, String setStatus, String currentUserID) {

            this.image = resultUri;
            this.name = setUserName;
            this.status = setStatus;
            this.uid = currentUserID;

        }

        public Item() {

        }
    }
     
     
    John Joe, May 3, 2019
    #15
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.