如何获取用于Firebase存储的下载URL和更新Firestore文档?

时间:2020-07-02 15:12:22

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

我一直在努力获取从我的应用上传到Firebase存储的图像的下载URL。 我想将此网址发送到Firestore数据库(不是实时数据库)。 我将itemImageUri设置为uri.toString(),但是在onCreate()方法中,itemImageUrl为null,并且在firestore中显示为null。我不能在CollectionRefernece addItemRef方法中使用onSuccess,因为它会给所有字符串变量带来错误:从内部类访问的变量需要声明为final。

public class AddItemActivity extends AppCompatActivity {

    public class AddItemActivity extends AppCompatActivity {
    public static final int PICK_IMAGE_REQUEST = 1;
    public static final String TAG = "Error!";
    public static final String UPLOAD_TAG = "Image uploaded";
    private Uri imageUri = null;
    private TextInputEditText textFieldTitle;
    private TextInputEditText textFieldDesc;
    private AutoCompleteTextView dropdownItemType;
    private TextInputEditText textFieldAddress;
    private TextInputEditText textFieldAvailability;
    private MaterialButton buttonSubmitItem;
    private MaterialButton buttonAddImage;
    private ImageView imageViewItem;
    private String itemImageUrl;
    private Bitmap bitmap;
    private Uri itemImageUri;

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

        imageViewItem = findViewById(R.id.imageView_camera);
        textFieldTitle = findViewById(R.id.textField_title);
        textFieldDesc = findViewById(R.id.textField_description);
        dropdownItemType = findViewById(R.id.dropdown_itemType);
        //Select type dropdown
        String[] itemTypes = new String[] {
                "Food",
                "Clothing",
                "Footwear"
        };
        ArrayAdapter<String> itemsDropdownAdpater = new ArrayAdapter<>(AddItemActivity.this, R.layout.dropdown_item_type, itemTypes);
        dropdownItemType.setAdapter(itemsDropdownAdpater);

        textFieldAddress = findViewById(R.id.textField_address);
        textFieldAvailability = findViewById(R.id.textField_availability);
        buttonAddImage = findViewById(R.id.button_addImage);
        buttonSubmitItem = findViewById(R.id.button_submitItem);

        buttonAddImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(AddItemActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(AddItemActivity.this, "Permission Denied", Toast.LENGTH_LONG).show();
                        ActivityCompat.requestPermissions(AddItemActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                    } else {
                        choseImage();
                    }
                } else {
                    choseImage();
                }
            }
        });

        buttonSubmitItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitItem();
            }
        });
    }

    private void choseImage() {
        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1, 1)
                .start(AddItemActivity.this);
    }

    private void submitItem() {
        String title = textFieldTitle.getText().toString();
        String desc = textFieldDesc.getText().toString();
        String type = dropdownItemType.getText().toString();
        String address = textFieldAddress.getText().toString();
        String availability = textFieldAvailability.getText().toString();
        
        if (title.trim().isEmpty() ||
                desc.trim().isEmpty() ||
                type.trim().isEmpty() ||
                availability.trim().isEmpty()) {
            Toast.makeText(this, "Fields cant be empty", Toast.LENGTH_SHORT).show();
            return;
        }
       
        handleUpload(bitmap);
        CollectionReference addItemRef = FirebaseFirestore.getInstance()
                .collection("ItemList");
        addItemRef.add(new ItemListModel(title, desc, type, address, availability, itemImageUrl));
        Toast.makeText(this, "Item added", Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                imageUri = result.getUri();
                imageViewItem.setImageURI(imageUri);
                imageViewItem.invalidate();
                BitmapDrawable drawable = (BitmapDrawable) imageViewItem.getDrawable();
                bitmap = drawable.getBitmap();
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }

    private void handleUpload(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        final StorageReference reference = FirebaseStorage.getInstance().getReference()
                .child("itemImages")
                .child(System.currentTimeMillis() + ".jpeg");

        reference.putBytes(baos.toByteArray())
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        getItemImageUrl(reference);
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.e(TAG, "onFailure: ", e.getCause());
                    }
                });
    }

    private void getItemImageUrl(StorageReference reference) {
        reference.getDownloadUrl()
                .addOnSuccessListener(new OnSuccessListener<Uri>() {
                    @Override
                    public void onSuccess(Uri uri) {
                        itemImageUrl = uri.toString();
                    }
                });

    }
}

3 个答案:

答案 0 :(得分:1)

确定下载URL需要调用服务器,这意味着它是异步发生的。因此,任何需要下载URL的代码都必须位于TextField("Text", text: Binding(get: {item.ProCode}, set: {item.ProCode = $0.prefix(5).trimmingCharacters(in: .whitespacesAndNewlines)})) 的{​​{1}}内部或从那里调用。

所以:

onSuccess

另请参阅:

答案 1 :(得分:0)

在NodeJS中,获取存储在Firebase Storage中的文档的链接。

//Unload Events
$(window).on('unload',function(e) {
  e = e || window.event;

  var timestamp = localStorage.getItem('timestamp')
  if(timestamp !=null && timestamp !=undefined){
    var TimeNow = new Date().getTime(), Difference  = TimeNow - timestamp ;

    if(Difference<20){
      //Browser Closed
      console.log('Browser Closed')
      localStorage.removeItem('timestamp');
 
      //Your logout function
      logout();
    }else{
      //Tab Closed
      console.log('Browser Tab Closed');
      localStorage.setItem('timestamp',new Date().getTime());
    }

  }else{
    //Other Event
    localStorage.setItem('timestamp',new Date().getTime());
  }
});

答案 2 :(得分:0)

首先将文件上传到存储设备,然后在addOnCompleteListener 上调用您的上传方法到数据库:

final StorageReference fileReference = storageRef.child(System.currentTimeMillis()
                + "." + getFileExtension(uriList.get(i)));
        uploadTask = fileReference.putFile(uriList.get(i));

        uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (!task.isSuccessful() && task.getException() != null) {
                    throw task.getException();
                }

                return fileReference.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    if(downloadUri != null) {
                        itemImageUrl = downloadUri.toString()
                        
                        // create your object
                        // upload your object to the database here
                    }

                }
            }
        });