-1

I m trying to upload image to firebase storage and as per my need it is going to storage perfectly but in firebase database I m facing 2 isssues

  1. When I upload image the download Url is not the same which I see in storage. It appears to be something like ""com.google.android.gms.tasks.zzu@590df7c"
  2. The details of uploaded image is not appending to logged in users node. Instead it is uploading to database in separate node.

    public class SecondActivity extends AppCompatActivity {
    private static final int CHOOSE_IMAGE = 101;
    String Database_Path = "users";
    String Storage_Path = "profilepics/";
    TextView textView;
    private ImageView imageView;
    EditText editText;
    Uri uriProfileImage;
    String downloadUri;
    ProgressBar progressBar;
     FirebaseAuth mAuth;
    String imageUrl;
    Button UploadButton;
    
    
    StorageReference storageReference;
    DatabaseReference databaseReference;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    
    mAuth = FirebaseAuth.getInstance();
    
    editText = (EditText) findViewById(R.id.editTextDisplayName);
    imageView = (ImageView) findViewById(R.id.imageView);
    UploadButton = (Button)findViewById(R.id.buttonSave);
    progressBar = (ProgressBar) findViewById(R.id.progressbar);
    
    
    storageReference = FirebaseStorage.getInstance().getReference();
    databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
    
    progressBar = new ProgressBar(SecondActivity.this)
       imageView.setOnClickListener(new View.OnClickListener() {
             @Override
          public void onClick(View v) {
                showimagechooser();
        }
    });
    
    UploadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
            // Calling method to upload selected image on Firebase storage.
    
            startActivity(new Intent(SecondActivity.this, DisplayProfile.class));
    
        }
    });
     }
    
    private void showimagechooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select profile Image"), CHOOSE_IMAGE);
    
     }
     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    super.onActivityResult(requestCode, resultCode, data);
    
    if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        uriProfileImage = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
            imageView.setImageBitmap(bitmap);
            uploadImageToFirebaseStorage(bitmap);
    
           } catch (IOException e) {
            e.printStackTrace();
           }
        }
     }
    
     private void uploadImageToFirebaseStorage(Bitmap bitmap) {
    final String TempImageName = editText.getText().toString().trim();
    
    FirebaseStorage storage = FirebaseStorage.getInstance();
    final StorageReference storageRef = storage.getReference();
    String userID=mAuth.getCurrentUser().getUid();
    System.out.println(userID);
    // this is how you set your desired name for the image
    final StorageReference ImagesRef = storageRef.child("images/"+mAuth.getCurrentUser().getUid()+".jpg");
    
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
    byte[] data = baos.toByteArray();
    final UploadTask uploadTask = ImagesRef.putBytes(data);
    
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.i("whatTheFuck:",exception.toString());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>(){
                                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                @Override
                                public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
                                    Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                                        @Override
                                        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) {
                                            if (!task.isSuccessful()) {
                                                Log.i("problem", task.getException().toString());
                                            }
    
                                            return ImagesRef.getDownloadUrl();
                                        }
                                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Uri> task) {
                                            if (task.isSuccessful()) {
                                                Uri downloadUri = task.getResult();
    
                                                DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users").child(mAuth.getCurrentUser().getUid());
                                                ref.child("imageURL").setValue(downloadUri.toString());
                                                ref.child("imageName").setValue(TempImageName);
    
    
                                            } else {
                                                Log.i("wentWrong","downloadUri failure");
                                            }
                                        }
                                    });
                                }
    });
    
     }
     }
    

Here is link to My database Database image

Thanks in advance

Mehul Kothari
  • 386
  • 1
  • 12
  • Hey @Mk, did my answer help you solve your problem? – PradyumanDixit Dec 09 '18 at 12:07
  • The way you get the download URL from an upload has changed. See the [documentation on getting a download URL after uploading a file](https://firebase.google.com/docs/storage/android/upload-files#get_a_download_url), or one of these questions https://stackoverflow.com/questions/53299915/how-to-get-offline-uploded-file-download-url-in-firebase, https://stackoverflow.com/questions/53127996/getdownloadurl-isnt-inputting-the-link-i-need/53128190#53128190, https://stackoverflow.com/questions/52730647/firebase-storage-bug-trying-to-insert-data-into-my-database/52740955#52740955 – Frank van Puffelen Dec 09 '18 at 14:09
  • nothing worked that's why I posted this question – Mehul Kothari Dec 09 '18 at 15:30

2 Answers2

1

Yes @Yupi is right, you're not correctly getting the correct url for your image. For getting the correct url of your uploaded image, you can use a code like this:

private void uploadFile(Bitmap bitmap) {

        FirebaseStorage storage = FirebaseStorage.getInstance();
        final StorageReference storageRef = storage.getReference();

         // this is how you set your desired name for the image
        final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();
        final UploadTask uploadTask = ImagesRef.putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.i("whatTheFuck:",exception.toString());
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
               // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (!task.isSuccessful()) {
                            Log.i("problem", task.getException().toString());
                        }

                        return ImagesRef.getDownloadUrl(); 
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();

                            DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());


                            Log.i("seeThisUri", downloadUri.toString());// This is the link or name you should use to save or set the image

                            ref.child("imageURL").setValue(downloadUri.toString());


                        } else {
                            Log.i("wentWrong","downloadUri failure");
                        }
                    }
                });
             }
        });

    }

This code also contains instances of how to upload url to the Firebase Database, and I think this might help you in your code.

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
0

I think you are not uploading image correctly that means you are not getting real image url. I think you are missing one part of code. So inside onSuccess(UploadTask.TaskSnapshot taskSnapshot) add:

storageReference2nd.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            String imageUrl = uri.toString() // this is your image url 
                           // which you want to send on database
                        }
                    });
Yupi
  • 4,402
  • 3
  • 18
  • 37