【问题标题】:Unable to put image url to Firestore database after uploading the image to firebase storage将图片上传到 Firebase 存储后,无法将图片网址放入 Firestore 数据库
【发布时间】:2020-01-17 06:06:26
【问题描述】:

我正在尝试将一些图像上传到 firestore 存储并将图像 URL 放入 firebase 数据库。图片上传成功,但图片 URL 未添加到数据库中。我认为可能导致此问题的问题是,在上传图像后将图像 URL 添加到 Hashmap,但数据库上传过程不等待 URL,而是在 Upload 任务之前将所有其他 HashMap 键添加到数据库返回网址。这样,所有其他键都会添加到数据库中,但不会添加图像 URL。在下面的代码中,产品 ID 已成功添加到数据库中,如果我未选择任何图像,它的 url 也会被添加为空的数据库,这工作正常,但如果我选择要上传的图像,到数据库的哈希图上传完成甚至在获取上传的图片 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;
        }
    }
}

【问题讨论】:

  • 发布问题后你去了哪里?
  • 得到了答案。

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


【解决方案1】:

你的代码

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

在之前执行

objectMap.put("image3_url",image_3_url)

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

尝试将值设置为onComplete() 内的数据库或使用不同的解决方法仅设置 url。

【讨论】:

  • 但是为什么它在执行图像部分之前执行 Firestore 部分?
【解决方案2】:

您忘记将 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();
                        }
                    });
                }
            }
        });
    }

现在您可以检查代码并找到您做错的地方。只需添加插入数据库的代码行。

谢谢。

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 2022-09-25
    • 2021-01-13
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多