为什么在点击上传按钮Android Firebase存储之前图像会自动上传?

时间:2018-03-01 07:56:21

标签: java android firebase firebase-realtime-database firebase-storage

您好我使用Android Firebase Storage上传照片,然后使用Glide将其显示在我的ImageView中。虽然他们确实工作我有一个问题,就是在我的谷歌硬盘上选择图像后,而不是在图像上传到服务器之前等待我点击上传按钮,图像会自动上传。

我的代码

 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);

            }
        });

1 个答案:

答案 0 :(得分:1)

当您从当前活动(MainActivity)启动活动时,要获取其结果,将调用startActivityForResult()方法。当您被重定向以打开诸如:相机,图库,Google云端硬盘等活动时,在获取您感兴趣的图像后,当返回当前活动时,自动调用的第一个方法是onActivityResult()。< / p>

正如我在您的代码中看到的那样,您还在onActivityResult()中添加了图片,这就是为什么您的图片会自动上传的原因。如果您希望这样,那么只需让onActivityResult()中的代码从uploadImage()方法中移除,否则请执行相反的操作。