将图像上传到Firebase存储后,无法将图像URL放入Firestore数据库

时间:2019-09-16 11:49:58

标签: java android google-cloud-platform google-cloud-firestore firebase-storage

我正在尝试将一些图像上传到Firestore存储,并将图像URL放入Firebase数据库。图像已成功上传,但未将图像URL添加到数据库中。我认为可能导致此问题的原因是,在上载图像后将图像URL添加到Hashmap中,但是数据库上传过程并未等待该URL,而是在上载任务之前将所有其他HashMap键添加到了数据库中返回URL。这样,所有其他键都被添加到数据库中,而不是图像URL。在下面的代码中,产品ID已成功添加到数据库中,如果我未选择任何图像,其URL也会被添加为空到数据库,这很好,但是如果我选择要上传的图像,则到数据库的哈希映射将完成甚至在获取上传的图片网址之前。

public class AddProductDataActivity extends AppCompatActivity {

    String productId;
    EditText productIdEditText;
    ImageView addProductImage3;

    Button addProductSubmit;

    final int IMAGE3_REQUEST = 30;

    Uri image3LocationPath;

    StorageReference objectStorageReference;
    FirebaseFirestore objectFireBaseFireStore;

    Map<String, String> objectMap = new HashMap<>();
    StorageReference img3Store;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product_data);

        brandNameEditText =(EditText) 
        addProductImage3 = (ImageView)  findViewById(R.id.add_product_image3);


        objectStorageReference = 
        FirebaseStorage.getInstance().getReference("images");
        objectFireBaseFireStore = FirebaseFirestore.getInstance();


        addProductImage3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent objectIntent = new Intent();
                objectIntent.setType("image/*");

                objectIntent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(objectIntent, IMAGE3_REQUEST);
            }
        });


        addProductSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productId = productIdEditText.getText().toString();

                if(image3LocationPath != null)
                {
                    final String image3Name = productId + "_image3." + getExtension(image3LocationPath);
                    img3Store = objectStorageReference.child(image3Name);
                    UploadTask imageUploadTask = img3Store.putFile(image3LocationPath);
                    imageUploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                        @Override
                        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                            if(!task.isSuccessful())
                            {
                                Toast.makeText(AddProductDataActivity.this, "Task Unsuccessful", Toast.LENGTH_SHORT).show();
                            }
                            return img3Store.getDownloadUrl();
                        }
                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                           @Override
                           public void onComplete(@NonNull Task<Uri> task) {
                               if(task.isSuccessful())
                               {
                                   String image_3_url = task.getResult().toString();
                                   objectMap.put("image3_url",image_3_url);
                               }
                               else
                               {
                               Toast.makeText(AddProductDataActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
                           }
                       }
                   });
               }
               else
               {
                   objectMap.put("image3_url","");
               }


               objectFireBaseFireStore.collection("images").document(productId).set(objectMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                   @Override
                   public void onSuccess(Void aVoid) {
                       Toast.makeText(AddProductDataActivity.this, "Product Added Successfully.", Toast.LENGTH_SHORT).show();
                   }
               }).addOnFailureListener(new OnFailureListener() {
                   @Override
                   public void onFailure(@NonNull Exception e) {
                       Toast.makeText(AddProductDataActivity.this, "Error in Adding Product. Please Try Again.\n"+e.getMessage(), Toast.LENGTH_SHORT).show();
                   }
               });
           }
       }

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

            case 30:

            try
            {
                if(resultCode == RESULT_OK && data != null && data.getData() != null)
                {
                    image3LocationPath = data.getData();
                    Bitmap objectBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image3LocationPath);

                    addProductImage3.setImageBitmap(objectBitmap);
                }
            }
            catch (Exception e)
            {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            break;

            default:
            break;

        }

        private String getExtension(Uri uri){
            try
            {
                ContentResolver objectContentResolver = getContentResolver();
                MimeTypeMap objectMimeTypeMap = MimeTypeMap.getSingleton();
                return objectMimeTypeMap.getExtensionFromMimeType(objectContentResolver.getType(uri));
            }
            catch (Exception e)
            {
                Toast.makeText(AddProductDataActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            return null;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您的代码

objectFireBaseFireStore.collection("images").document(productId).set(objectMap)

先执行

objectMap.put("image3_url",image_3_url)

这意味着当您设置网址时,您的objectMap没有密钥image3_url

尝试在onComplete()内为数据库设置值,或使用其他解决方法仅设置url。

答案 1 :(得分:0)

您忘记将HashMap添加到Firebase的数据库引用中。

这是我当前项目代码的参考。

private void uploadVideo() {
        StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
        final StorageReference riversRef = mStorageRef.child(Constants.STORAGE_PATH + "/" + mFinalUploadUri.getLastPathSegment());
        riversRef.putFile(mFinalUploadUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful()) {
                    throw Objects.requireNonNull(task.getException());
                }
                // Continue with the task to get the download URL
                return riversRef.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    FirebaseFirestore database = FirebaseFirestore.getInstance();

                    String mSelectedCategory = binding.categorySpinner.getSelectedItem().toString();
                    DocumentReference newDocumentReference = database.collection(PENDING_PATH).document();

                    VideoModel videoModel = new VideoModel();
                    videoModel.setDocumentId(newDocumentReference.getId());
                    videoModel.setTitle(mTitle);
                    videoModel.setCategory(mSelectedCategory);
                    //videoModel.setTime(FieldValue.serverTimestamp());

                    videoModel.setUrl(downloadUri != null ? downloadUri.toString() : null);

                    newDocumentReference.set(videoModel).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            binding.progressBar.setVisibility(View.GONE);
                            binding.button.setVisibility(View.VISIBLE);
                            binding.videoView.setVisibility(View.GONE);
                            selectedUri = null;
                            Toast.makeText(AdminVideoUploadActivity.this, R.string.uploaded_successfully, Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(AdminVideoUploadActivity.this, R.string.failed_to_upload, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

现在,您可以检查代码并查找在哪里做错了。只需添加插入数据库的代码行即可。

谢谢。