0

I'm using Firebase Storage to upload images from an Android app. So when I click photoBtn button, image_picker opens, but when I select an image, the URI is still null.

Here is my code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        StorageReference photoRef=mEventPhotoReference.child(selectedImageUri.getLastPathSegment());

        photoRef.putFile(selectedImageUri)
                .addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        // When the image has successfully uploaded, we get its download URL
                        downloadUrl = taskSnapshot.getDownloadUrl();
                        Toast.makeText(MainActivity.this,"got the uri",Toast.LENGTH_LONG).show();
                    }

                });

    }


}

//DISPLAY INPUT DIALOG
private void displayInputDialog()
{
    Dialog d=new Dialog(this);
    d.setTitle("Save To Firebase");
    d.setContentView(R.layout.input_dialog);

    nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);
    grpTxt= (EditText) d.findViewById(R.id.propellantEditText);
    descTxt= (EditText) d.findViewById(R.id.descEditText);
    Button saveBtn= (Button) d.findViewById(R.id.saveBtn);
    Button photoBtn=(Button)d.findViewById(R.id.photoBtn);
    linkTxt = (EditText) d.findViewById(R.id.linkEditText);



    photoBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);

        }
    });


    //SAVE
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //GET DATA
            String name=nameEditTxt.getText().toString();
            String propellant=grpTxt.getText().toString();
            String desc=descTxt.getText().toString();
            String link=linkTxt.getText().toString();
            Long tsLong = System.currentTimeMillis()/1000;
            String ts = tsLong.toString();


            //SET DATA
            Spacecraft s=new Spacecraft();

            if(downloadUrl==null){
                Toast.makeText(MainActivity.this,"Photo is necessary to add an Event",Toast.LENGTH_SHORT).show();
            }else {
                s.setName(name);
                s.setPropellant(propellant);
                s.setDescription(desc);
                s.setLink(link);
                s.setImageUrl(downloadUrl.toString());
                s.setTimestamp(ts);
            }
            //SIMPLE VALIDATION
            if(name != null && name.length()>0)
            {
                //THEN SAVE
                if(helper.save(s))
                {
                    //IF SAVED CLEAR EDITXT
                    nameEditTxt.setText("");
                    grpTxt.setText("");
                    descTxt.setText("");
                    linkTxt.setText("");
                    downloadUrl=null;



                    adapter=new MyAdapter(MainActivity.this,helper.retrieve());
                    rv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                }
            }else
            {
                Toast.makeText(MainActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
            }

        }
    });

    d.show();
}

Can someone please help me why onSuccess method is never executed and downloadUrl is always null?

AL.
  • 36,815
  • 10
  • 142
  • 281

2 Answers2

1

You might consider implementing an onFailureListener to see why it's failing. If on success isn't being called it's because it's not successful. That's where the failure listener comes in.

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle unsuccessful uploads
    }
}).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.
        Uri downloadUrl = taskSnapshot.getDownloadUrl();
    }
});

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

Michael Vescovo
  • 3,741
  • 4
  • 32
  • 45
  • I found the answer , it was actually the rules that were stopping the image from being uploaded, u changed the rules and everything works fine now – Mohd Sohail Ahmed Feb 26 '17 at 18:49
  • Ok but you would have been able to find this from checking the failure exception. How did you find the answer? – Michael Vescovo Feb 26 '17 at 18:54
  • Strangely there was something wrong with android studio it wasn't displaying firebase exception log in log messages , i restarted android studio and then it displayed the exception message – Mohd Sohail Ahmed Feb 26 '17 at 18:56
0

Check out my answer here . I'm providing a simple wrapper to get images and receive them correctly

Community
  • 1
  • 1
MohammedAlSafwan
  • 872
  • 1
  • 8
  • 25
  • I just realised that my intent returns data but in onActivityResult the addOnSuccessListener isn't executed , can you tell me what might be the problem – Mohd Sohail Ahmed Feb 26 '17 at 18:11
  • if you checked my answer you would of seen that you have to change `requestCode == RC_PHOTO_PICKER` to `(requestCode & 0xffff) == RC_PHOTO_PICKER` to get the correct hex value. – MohammedAlSafwan Feb 26 '17 at 18:14
  • unfortunately it's not working , the line photoRef.putFile(selectedImageUri) .addOnSuccessListener still doesn't executes – Mohd Sohail Ahmed Feb 26 '17 at 18:19
  • does it actually reach that part ? try to put a Log there and see if it actually get inside of your if statement – MohammedAlSafwan Feb 26 '17 at 18:20
  • I must be kicking myself my code was working fine the reason it was not executing onSuccess method was i forgot to make my firebase rules public , anyways thanks for your help issue is resolved – Mohd Sohail Ahmed Feb 26 '17 at 18:37