将图片上传(ACTION_IMAGE_CAPTURE)到Firebase存储 [英] Uploading image (ACTION_IMAGE_CAPTURE) to Firebase storage

查看:1032
本文介绍了将图片上传(ACTION_IMAGE_CAPTURE)到Firebase存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:关于这个问题的讨论已经进行到另一个问题:请检查出来!我做了一些操作(遵循Android文档),但仍然有同样的问题。

所以我在这里试图做一个简单的任务,捕捉图像与相机并将其上传到我的Firebase上的存储数据库。我有以下按钮来完成这项工作:

$ p $ b $ ca $ b_capture.setOnClickListener(new View.OnClickListener(){
@覆盖
public void onClick(View view){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
}
}) ;

以及以下代码进行上传:

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

if(requestCode == CAMERA_REQUEST_CODE&& resultCode == RESULT_OK){
progressDialog.setMessage(Uploading ...);
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storage.child(Photos)。child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener< UploadTask.TaskSnapshot>(){
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
Toast.makeText (MainActivity.this,Upload Successful!,Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
})。addOnFailureListener(new OnFailureListener(){
@Override
public void onFailure(@NonNull Exception e){
Toast.makeText(MainActivity.this,Upload Failed!,Toast.LENGTH_SHORT).show();
}
});






$ b $ p $在应用程序中我可以拍照,但是在我确认了APP CRASHES的照片之后,我得到以下错误:

pre $ 引起:java.lang.NullPointerException:尝试在空对象引用


$ b上调用虚方法'java.lang.String android.net.Uri.getLastPathSegment $ b

所以,我明白Uri里没有任何东西,但是我对可以做什么感到困惑。需要帮助。
$ b

是的,我已经检查了所有的权限,Firebase连接,Gradle同步等。

解决方案

您需要重新阅读文档并按照该示例创建一个文件,并在图像捕捉意图中存储其 Uri 。这是您需要添加的文档中的代码:

  String mCurrentPhotoPath; 
$ b $ private文件createImageFile()抛出IOException {
//创建一个图像文件名
String timeStamp = new SimpleDateFormat(yyyyMMdd_HHmmss)。
String imageFileName =JPEG_+ timeStamp +_;
文件storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,/ *前缀* /
.jpg,/ *后缀* /
storageDir / *目录* /
);

//保存文件:用于ACTION_VIEW意图的路径
mCurrentPhotoPath = image.getAbsolutePath();
返回图片;


private void dispatchTakePictureIntent(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//确保有相机活动来处理意图
if(takePictureIntent.resolveActivity(getPackageManager())!= null){
//创建照片应该去的文件
档案photoFile = null;
尝试{
photoFile = createImageFile();
} catch(IOException ex){
//创建文件
时发生错误...
}
//仅在文件成功创建时继续
if(photoFile!= null){
Uri photoURI = FileProvider.getUriForFile(this,
com.example.android.fileprovider,
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
startActivityForResult(takePictureIntent,REQUEST_TAKE_PHOTO);




$ b b_capture.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
dispatchTakePictureIntent()

// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// startActivityForResult(intent,CAMERA_REQUEST_CODE);
}
});


EDIT: The discussion on this issue has been carried to another question: Image capture with camera & upload to Firebase (Uri in onActivityResult() is null) PLEASE check it out! I did some manipulations (following the android documentation) but still getting same problem.

So here I'm trying to do a simple task of capturing an image with camera and uploading it to my storage database on Firebase. I have the following button to do the job:

b_capture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);
        }
    });

and the following code for the upload:

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

    if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        progressDialog.setMessage("Uploading...");
        progressDialog.show();
        Uri uri = data.getData();
        StorageReference filepath = storage.child("Photos").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
            }
        });
      }
    }

in the app I'm able to take picture, but after I confirm the picture taken the APP CRASHES and I get the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference

So, I understand that the "Uri" does not have anything in it, but I'm confused about what can be done. Need help.

And yes, I've checked all permissions, Firebase connections, Gradle sync etc.

解决方案

You need to re-read the documentation and follow the example to create a file and store its Uri in the image capture intent. This is the code from the documentation you need to add:

String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        ".jpg",         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ...
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                                                  "com.example.android.fileprovider",
                                                  photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}


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

            //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //startActivityForResult(intent, CAMERA_REQUEST_CODE);
        }
    });

这篇关于将图片上传(ACTION_IMAGE_CAPTURE)到Firebase存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆