1
votes

I'm trying to make a chatting app in which I want users to upload images, and I'm using Firebase RealTime Database to store user's data. taskSnapshot.downloadUrl() method is deprecated, as I've used a different approach to upload images to Firebase as shown in documentation

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

and this StackOverflow

post:taskSnapshot.getDownloadUrl() is deprecated But still, image is not uploading to the database.

And I've also tried things like clean project, rebuild project, Invalidate and Restart.

This is the code I'm using to upload images to Firebase RealTime Database:

    // ImagePickerButton shows an image picker to upload an image for a 
     message
    mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/jpeg");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
        }
    });

and then in onActivityResults method :

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable 
Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SIGN_IN) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(MainActivity.this, "Signed-In", 
        Toast.LENGTH_SHORT).show();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(MainActivity.this, "Signed-In Cancel", 
        Toast.LENGTH_SHORT).show();
            finish();
        } else if (requestCode == RC_PHOTO_PICKER && resultCode == 
          RESULT_OK) {

            Uri selectedUri = data.getData();
            final StorageReference storageReference = mChatPhotosStorageReference.
                    child(selectedUri.getLastPathSegment());
            UploadTask uploadTask = storageReference.putFile(selectedUri);
            Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                @Override
                public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }

                    return storageReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUrl = task.getResult();
                        FriendlyMessage message = new FriendlyMessage(null, mUsername, downloadUrl.toString());
                         mMessageDatabaseReference.push().setValue(message);
                    }
                }
            });

This is the Github link for full project: https://github.com/harshabhadra/FriendlyChat

1
You're not doing any error handling. The task could fail, but you're only writing code that runs if the task completes successfully. If there is an error, you'll never know that it happened. - Doug Stevenson
Have you tried to handle the errors? Do y ou get any message? Please responde with @. - Alex Mamo
@AlexMamo yes I've tried to handle the errors and I didn't' get any message - Harsha Bhadra

1 Answers

0
votes

Use this to upload photo to Firebase Storage in byte

private void uploadImage(byte[] data) {
        submitButton.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);

        final String userId = DatabaseContants.getCurrentUser().getUid();
        photo_description_edit_text.setVisibility(View.GONE);
        StorageMetadata metadata = new StorageMetadata.Builder()
                .setContentType("image/webp")
                .build();

        final String photoName = System.currentTimeMillis() + "_byUser_" + userId;
        StorageReference imageRef = StorageConstants.getImageRef(photoName + ".webp");
        UploadTask uploadTask = imageRef.putBytes(data, metadata);

        final Resources res = getResources();

        uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double progress = 100.0 * (taskSnapshot.getBytesTransferred() /
                        taskSnapshot.getTotalByteCount());
                progressBar.setProgress((int) progress);
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size,
                // content-type, and download URL.
                Log.d(LOG_TAG, "Image is successfully uploaded: " + taskSnapshot.getMetadata());

                Uri downloadUrl = taskSnapshot.getDownloadUrl();

                Analytics.registerUpload(activity, userId);

                PhotoModel photoModel = new PhotoModel(userId, photoDescription, "none",
                        0, 0, rotation, photoName + ".webp");

                DatabaseContants.getPhotoRef().child(photoName).setValue(photoModel);

                Utils.photosUploadedCounter++;
                if (Utils.photosUploadedCounter % 2 == 0) {
                    if (mInterstitialAd.isLoaded()) {
                        mInterstitialAd.show();
                    } else {
                        Log.d("TAG", "The interstitial wasn't loaded yet.");
                    }
                }

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                NotificatonConstants.sendNotification(activity,
                        res.getString(R.string.failure_title),
                        res.getString(R.string.failure_message),
                        NotificatonConstants.UPLOAD_ID);
            }
        }).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                NotificatonConstants.sendNotification(activity,
                        res.getString(R.string.success_title),
                        res.getString(R.string.success_message),
                        NotificatonConstants.UPLOAD_ID);
            }
        });
    }