Yamiess
Yamiess

Reputation: 251

Why is image automatically gets uploaded before even clicking the upload button Android Firebase Storage?

Hello I'm using Android Firebase Storage to upload the photos and then using Glide to show them into my ImageView. While they do indeed work I have a problem which is after selecting the image on my google drive, instead of waiting for me to click the upload button before the image gets uploaded to the server, the image would automatically upload.

My code

 imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            chooseImage();
        }
    });
    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage();
        }
    });
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String firstname = dataSnapshot.child("first").getValue(String.class);
            String secondname = dataSnapshot.child("second").getValue(String.class);
            String number = dataSnapshot.child("number").getValue(String.class);
            String gender = dataSnapshot.child("gender").getValue(String.class);
            String email = dataSnapshot.child("email").getValue(String.class);
            String date = dataSnapshot.child("date").getValue(String.class);
            String url = dataSnapshot.child("image").getValue(String.class);
            userfirstName.setText(firstname);
            usersecondName.setText(secondname);
            userNumber.setText(number);
            userGender.setText(gender);
            userEmail.setText(email);
            userDate.setText(date);

            Glide.with(userMain.this)
                    .load(url)
                    .into(imageView);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return view;
}

private void uploadImage() {
    if(filePath != null)
    {
        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setTitle("Uploading...");
        progressDialog.show();

        StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Toast.makeText(getContext(), "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(getContext(), "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded "+(int)progress+"%");
                    }
                });
    }
}

private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
    String useruid=user.getUid();
    final DatabaseReference img = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(useruid);
    if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null )
    {
        filePath = data.getData();
        StorageReference filepath= storageReference.child("Images").child(filePath.getLastPathSegment());
        filepath.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                String downloadUrl = taskSnapshot.getDownloadUrl().toString();
                img.child("image").setValue(downloadUrl);
                imageView.setImageURI(filePath);

            }
        });

Upvotes: 1

Views: 91

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138999

When you start an activity from your current activity (MainActivity), to get the result for it, the startActivityForResult() method is called. When you are redirected to open an activity like: Camera, Gallery, Google Drive etc., after taking the image that you are interested in, when coming back to current activity, first method that is automatically called is onActivityResult().

As I see in your code, your are adding the image also in the onActivityResult(), that's why your image is uploaded automatically. If you want it to be this way, then just let the code in the onActivityResult() and remove it from uploadImage() method, otherwise do the opposite.

Upvotes: 1

Related Questions