2
votes

I have created an app running with Firebase Storage. The idea is that you select an Image from your Photo Gallery and then Upload it to Firebase Storage. The connection with Firebase seems to work fine, I can select an Image. The problem arises when I push the Submit Button to upload it to Firebase.

When I click it one time, nothing happens.

When I click it a few times, I get the message "an unknown error occurred, please check the HTTP result code and inner exception"..

What should I do, looking for advice..

From the Manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>

From the Activity:

public class PostActivity extends AppCompatActivity {

private static final int GALLERY_REQUEST = 2;
private Uri uri = null;
private ImageButton imageButton;
private EditText editName;
private EditText editDescription;
private StorageReference storageReference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);
    //reference the two edittext Views, initialize them
    editName = (EditText) findViewById(R.id.editName);
    editDescription = (EditText) findViewById(R.id.editDescription);

    //add the reference to the storagereference, initialize it
    storageReference = FirebaseStorage.getInstance().getReference();
}

public void ImageButtonClicked (View view){
    Intent galleryintent = new Intent (Intent.ACTION_GET_CONTENT);
    galleryintent.setType("Image/*");  
    startActivityForResult(galleryintent, GALLERY_REQUEST);
}

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

if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK){

uri = data.getData();
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setImageURI(uri);
    }
}

public void submitButtonClicked (View view){

    String titleValue = editName.getText().toString().trim();
    String titleDescription = editDescription.getText().toString().trim();

    if (!TextUtils.isEmpty(titleValue) && !TextUtils.isEmpty(titleDescription)){

        StorageReference filePath = storageReference.child("PostImage").child(uri.getLastPathSegment());

        filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

Uri downloadurl = taskSnapshot.getDownloadUrl();
Toast.makeText(PostActivity.this,"uploadcomplete",Toast.LENGTH_LONG).show();

            }
        });
filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

       Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
4

4 Answers

3
votes

Try this method for image upload to firebase storage:

private void uploadMethod() {
        progressDialog();
        FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
        StorageReference storageReferenceProfilePic = firebaseStorage.getReference();
        StorageReference imageRef = storageReferenceProfilePic.child("Your Path" + "/" + "Image Name" + ".jpg");

        imageRef.putFile(imageUri)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        //if the upload is successful
                        //hiding the progress dialog
                        //and displaying a success toast
                        dismissDialog();
                        String profilePicUrl = taskSnapshot.getDownloadUrl().toString();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        //if the upload is not successful
                        //hiding the progress dialog
                        dismissDialog();
                        //and displaying error message
                        Toast.makeText(getActivity(), exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        //calculating progress percentage
//                        double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//                        //displaying percentage in progress dialog
//                        progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                    }
                });

    }
2
votes

I have found an answer through the code of Rahul Chandrabhan. What I have changed is to remove the last part of the following method:

StorageReference filePath = 
storageReference.child("PostImage").child(uri.getLastPathSegment());

TO 

StorageReference filePath = storageReference.child("PostImage");
0
votes

To perform image upload on firebase use below method:

void uploadFile(String pathToFile, String fileName, String serverFolder, String contentType) {
    if (pathToFile != null && !pathToFile.isEmpty()) {

        File file = new File(pathToFile);
        if (file.exists()) {

            Uri uri = Uri.fromFile(new File(pathToFile));

            // Create a storage reference from our app
            mStorageRef = mFirebaseStorage.getReference();

            // Create a reference to "mountains.jpg"
            //StorageReference mountainsRef = storageRef.child(fileName);

            // Create a reference to 'images/mountains.jpg'
            StorageReference mountainImagesRef = mStorageRef.child(serverFolder+"/" + fileName);
            StorageMetadata metadata = null;
            if (contentType != null && !contentType.isEmpty()) {
                // Create file metadata including the content type
                metadata = new StorageMetadata.Builder()
                        .setContentType(contentType)
                        .build();
            }


            if (metadata != null) {
                uploadFileTask = mountainImagesRef.putFile(uri, metadata);
            } else {
                uploadFileTask = mountainImagesRef.putFile(uri);
            }

            uploadFileTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    hideProgressDialog();
                    exception.printStackTrace();
                    Log.e(TAG,exception.getMessage());
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadFailure(exception.getMessage());
                    }
                }
            });
            uploadFileTask.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.
                    hideProgressDialog();
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    Log.e(TAG, "Upload is success "+ downloadUrl);
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadSuccess("Upload is success "+ downloadUrl.toString(), downloadUrl.toString());
                    }
                }
            });
            // Observe state change events such as progress, pause, and resume
            uploadFileTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                    hideProgressDialog();
                    double progressPercent = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    progressPercent = Double.parseDouble(FirebaseUtil.formatDecimal(progressPercent,2));
                    Log.e(TAG, "File Upload is " + progressPercent + "% done");
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadProgress(progressPercent);
                    }
                }
            });
            uploadFileTask.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
                    hideProgressDialog();
                    Log.e(TAG, "Upload is paused");
                    if (firebaseUploadCallback!=null)
                    {
                        firebaseUploadCallback.onFirebaseUploadPaused("Upload is paused");
                    }
                }
            });
        }
        else
        {
            hideProgressDialog();
            Log.e(TAG, "Upload file does not exists");
            if (firebaseUploadCallback!=null)
            {
                firebaseUploadCallback.onFirebaseUploadFailure("Upload file does not exists");
            }
        }
    }else
    {
        hideProgressDialog();
        Log.e(TAG,"pathToFile cannot be null or empty");
        if (firebaseUploadCallback!=null)
        {
            firebaseUploadCallback.onFirebaseUploadFailure("pathToFile cannot be null or empty");
        }
    }
}

Make a call this method as below:

public void uploadDummyPicture(String email, String imagePath){
    if (imagePath == null) {
        return;
    }
    if (!isValidEmail(email)) {
        return;
    }
    String serverFolder = "dummy_images/" + email; //path of your choice on firebase storage server
    String fileName = "DummyPhoto.png";
    uploadFile(imagePath, fileName, serverFolder, "image/png");
    showProgressDialog();
}

Make sure to check the firebase storage rules before using above code as explained here. If the rules have firebase authentication required, then first complete firebase authentication of the current user and then start uploading the file.

I hope this answer will you solve your problem.

0
votes

In my case, the URI which I was fetching on the onActivityResult function was just not in the right format. Previously I was parsing like this

uri=Uri.parse(your image path)

but after changing to this it worked

uri=Uri.fromFile(new File(your image path))

the upload function

public void upload()
    {
        if(uri!=null)
        {

            progressBar.setVisibility(View.VISIBLE);
            progressBar_tv.setVisibility(View.VISIBLE);
            Log.i("URI",uri.getPath());
            UploadTask uploadTask=sRef.putFile(uri);
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(VideoEditAndUploadActivity.this, "Upload Failed:"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();;
                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(VideoEditAndUploadActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.INVISIBLE);
                    progressBar_tv.setVisibility(View.INVISIBLE);
                }
            }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                    updateUploadProgress(snapshot);
                }
            });
        }
        else{
            Toast.makeText(this, "Video Uri is null: please choose a video first!", Toast.LENGTH_SHORT).show();
        }
    }

the update progress bar function

@SuppressLint("DefaultLocale")
    private void updateUploadProgress(UploadTask.TaskSnapshot snapshot) {
        long fileSize=snapshot.getTotalByteCount();
        long uploadBytes=snapshot.getBytesTransferred();
        long progress=(100*uploadBytes)/fileSize;

        progressBar.setProgress((int) progress);
        progressBar_tv.setText(String.format("%d%%", progress));
    }