Search code examples
firebasefirebase-storagepicasso

Unable to obtain user profile image from Firebase Storage


I'm currently working on a settings page for my app and have been trying to obtain the user profile image from the firebase storage. I am able to upload the picture from the storage.

However, the app does not produce the image onto the activity itself. Is there something wrong with my code?

Original placeholder image disappears when I try to obtain image from firebase storage.

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background">

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_chat_toolbar"
        android:background="@color/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
    </androidx.appcompat.widget.Toolbar>

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="85dp"
        app:civ_border_color="@color/colorPrimary"
        android:src="@drawable/pikachu"
        app:civ_border_width="2dp" />


    <EditText
        android:id="@+id/setting_username"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/profile_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:drawableLeft="@drawable/ic_action_name"
        android:hint="Username"
        android:inputType="textMultiLine" />

    <EditText
        android:id="@+id/set_profile_status"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/setting_username"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:drawableLeft="@drawable/ic_user_status"
        android:hint="Hey, I'm available now!"
        android:inputType="textMultiLine" />


    <Button
        android:id="@+id/setting_updatebtn"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/set_profile_status"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:background="@drawable/btn_rect"
        android:text="Update Settings" />

</RelativeLayout>
  1. Java

    package com.shiminu1521462c.fyp_2;
    
    
    
    
    
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    
    import android.text.TextUtils;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.bumptech.glide.Glide;
    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.database.DataSnapshot;
    import com.google.firebase.database.DatabaseError;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.database.ValueEventListener;
    import com.google.firebase.storage.FirebaseStorage;
    import com.google.firebase.storage.StorageReference;
    import com.google.firebase.storage.UploadTask;
    import com.squareup.picasso.Picasso;
    import com.theartofdev.edmodo.cropper.CropImage;
    import com.theartofdev.edmodo.cropper.CropImageView;
    
    import java.io.File;
    import java.util.HashMap;
    
    import de.hdodenhof.circleimageview.CircleImageView;
    
    public class SettingActivity extends AppCompatActivity {
    
    private EditText etUsername, etUserStatus;
    private Button changeSettings;
    private CircleImageView userProfileImage;
    private Toolbar mToolbar;
    private String currentUserID;
    
    private FirebaseAuth mAuth;
    private DatabaseReference RootRef;
    
    private static final int GalleryPick = 1;
    private StorageReference UserProfileImageRef;
    private ProgressDialog LoadingBar;
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
    
        mToolbar = (Toolbar) findViewById(R.id.main_chat_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Settings");
    
        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        RootRef = FirebaseDatabase.getInstance().getReference();
        UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");
    
        InitializeFields();
    
        etUsername.setVisibility(View.INVISIBLE);
    
        changeSettings.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() {
    
        changeSettings = (Button) findViewById(R.id.setting_updatebtn);
        etUsername = (EditText) findViewById(R.id.setting_username);
        etUserStatus = (EditText) findViewById(R.id.set_profile_status);
        userProfileImage = (CircleImageView) findViewById(R.id.profile_image);
        LoadingBar = new ProgressDialog(this);
    }
    
    @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 while your profile image is uploading...");
                LoadingBar.setCanceledOnTouchOutside(false);
                LoadingBar.show();
    
                final Uri resultUri = result.getUri();
                StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
    
                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(Task<UploadTask.TaskSnapshot> task) {
    
                        if (task.isSuccessful()) {
                            Toast.makeText(SettingActivity.this, "Profile Image Uploaded Successfully!", Toast.LENGTH_SHORT).show();
    
                            final 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(Task<Void> task) {
                                            if(task.isSuccessful()){
    
                                                Toast.makeText(SettingActivity.this, "Image saved in Database successfully!", Toast.LENGTH_SHORT).show();
                                                LoadingBar.dismiss();
                                            }else{
    
                                                String message = task.getException().toString();
                                                Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                LoadingBar.dismiss();
                                            }
                                        }
                                    });
                        } else {
                            String message = task.getException().toString();
                            Toast.makeText(SettingActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                            LoadingBar.dismiss();
                        }
                    }
                });
    
            }
        }
    }
    
    private void UpdateSettings() {
        String setUsername = etUsername.getText().toString();
        String setStatus = etUserStatus.getText().toString();
    
        if (TextUtils.isEmpty(setUsername)) {
    
            Toast.makeText(this, "Please enter your username..", Toast.LENGTH_SHORT).show();
        }
        if (TextUtils.isEmpty(setStatus)){
    
            Toast.makeText(this, "Please set a 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()) {
    
                                sendUserToDashboardActivity();
                                Toast.makeText(SettingActivity.this, "Profile updated successfully!", Toast.LENGTH_SHORT).show();
                            } else {
    
                                String message = task.getException().toString();
                                Toast.makeText(SettingActivity.this, "Error: " + message, 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();
    
                            etUsername.setText(retrieveUsername);
                            etUserStatus.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();
    
                            etUsername.setText(retrieveUsername);
                            etUserStatus.setText(retrieveStatus);
    
                        } else {
                            etUsername.setVisibility(View.VISIBLE);
                            Toast.makeText(SettingActivity.this, "Please set and update profile information..", Toast.LENGTH_SHORT).show();
                        }
                    }
    
                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
    
                    }
                });
    }
    
    
    private void sendUserToDashboardActivity() {
        Intent mainIntent = new Intent(SettingActivity.this, DashboardActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mainIntent);
        finish();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent myIntent = new Intent(getApplicationContext(), DashboardActivity.class);
        startActivityForResult(myIntent, 0);
        return true;
    }
    
    }
    

Thank you.


Solution

  • I finally managed to solve my issue! This is the altered code, hopefully it helps others who need it! :)

     final Uri resultUri = result.getUri();
                    final StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
                    filePath.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
    
                                    final String downloadUrl = uri.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(SettingActivity.this, "Profile image stored to firebase database successfully.", Toast.LENGTH_SHORT).show();
                                                        LoadingBar.dismiss();
                                                    } else {
                                                        String message = task.getException().getMessage();
                                                        Toast.makeText(SettingActivity.this, "Error Occurred..." + message, Toast.LENGTH_SHORT).show();
                                                        LoadingBar.dismiss();
                                                    }
                                                }
                                            });
                                }
                            });
                        }