user14054849
user14054849

Reputation:

How to insert image URL into firestore database after uploading an image in android studio?

I created an upload image functionality in my app. The image uploads and shows for the user and returns "uploaded" upon success.

Now when the user closes the app and opens again it wont show the image because it is not stored in his unique database file in the field of profileImage.

I am storing the image in the storage datastore.

I want to store the same image url that is being stored in the storage to be in the current users field in the database.

But the code I've written still doesn't insert the required value of the image url.

Here is my code so far:

FirebaseFirestore fStore;
FirebaseStorage storage;
StorageReference storageReference;

FirebaseAuth fAuth;
String UID;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;


fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    userImage = findViewById(R.id.profile_userImg);

    userImage.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
        @Override
        public void onClick(View view) {
            chooseImage();
        }
    });

}



@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Choose a Profile Image"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            userImage.setImageBitmap(bitmap);
            if (filePath != null) {
                StorageReference ref = storageReference.child("Users Profile/" + UUID.randomUUID().toString());
                ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        UID = fAuth.getCurrentUser().getUid();
                        DocumentReference documentReference = fStore.collection("users").document(UID);
                        Map < String, Object > user = new HashMap < > ();
                        user.put("profileImage", PICK_IMAGE_REQUEST);
                        Toast.makeText(ProfileActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(ProfileActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 2374

Answers (3)

parth tagalpallewar
parth tagalpallewar

Reputation: 1

storageRef.child(path).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Glide.with(getApplicationContext()).load(uri.toString()).into(img);
        }
    });

Upvotes: 0

The file path cannot be used like that, as a reference to download an image. Instead you need to get a download url that is provided by firebase, change your code like this:

 StorageReference ref = storageReference.child("Users Profile/" + UUID.randomUUID().toString());
        UploadTask uploadTask = ref.putFile(filePath);

        Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (task.isSuccessful()) {
                    //here the upload of the image finish
                }

                // Continue the task to get a download url
                return ref.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult(); //this is the download url that you need to pass to your database
                    //Pass the url to your reference
                    UID = fAuth.getCurrentUser().getUid();
                    DocumentReference documentReference = fStore.collection("users").document(UID);
documentReference.update("profileImage", downloadUri);
                    Toast.makeText(ProfileActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                } else {
                    / Handle failures
                    // ...
                }
            }
        });

You can see in more detail here: https://firebase.google.com/docs/storage/android/upload-files#java_1

Upvotes: 3

Doug Stevenson
Doug Stevenson

Reputation: 317760

Your code doesn't actually write anything to the DocumentReference you created. You will need a call to set():

DocumentReference documentReference = fStore.collection("users").document(UID);
documentReference.set(...)

You will need to pass an object or Map to set to tell it what to store in the document, as illustrated in the documentation.

Upvotes: 0

Related Questions