【问题标题】:Image capture with camera & upload to Firebase (Uri in onActivityResult() is null)使用相机拍摄图像并上传到 Firebase(onActivityResult() 中的 Uri 为空)
【发布时间】:2017-04-04 06:47:43
【问题描述】:

所以我遇到了一个问题,之前在我提出的问题中提到过:Uploading image (ACTION_IMAGE_CAPTURE) to Firebase storage

我已经搜索了更多问题,并应用了 Android Studio 文档:https://developer.android.com/training/camera/photobasics.html#TaskPhotoView

所以,在你阅读代码之前,我基本上想说需要什么:我只想用相机拍摄一张照片,然后直接上传到 Firebase 存储.为此,我需要 Uri 来包含我刚刚拍摄的照片 (Uri.getLastPathSegment()),但是我仍然无法成功。

现在,这就是我的代码的样子(仅相关部分): AndroidManifest.xml

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
</provider>

我有 res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"   path="Android/data/com.serjardovic.firebasesandbox/files/Pictures" />
</paths>

最后是 MainActivity.java

public class MainActivity extends AppCompatActivity {

private Button b_gallery, b_capture;
private ImageView iv_image;
private StorageReference storage;
private static final int GALLERY_INTENT = 2;
private static final int CAMERA_REQUEST_CODE = 1;
private ProgressDialog progressDialog;

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, CAMERA_REQUEST_CODE);
        }
    }
}


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

    storage = FirebaseStorage.getInstance().getReference();

    b_gallery = (Button) findViewById(R.id.b_gallery);
    b_capture = (Button) findViewById(R.id.b_capture);
    iv_image = (ImageView) findViewById(R.id.iv_image);

    progressDialog = new ProgressDialog(this);

    b_capture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            dispatchTakePictureIntent();

        }
    });
}

@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();
            }
        });
        }
    }
}

需要解决方案!不过,在我拍照并按下确认按钮后,应用程序崩溃了,我收到以下崩溃报告:

java.lang.RuntimeException:将结果 ResultInfo{who=null, request=1, result=-1, data=null} 传递给活动 {com.serjardovic.firebasesandbox/com.serjardovic.firebasesandbox.MainActivity} 失败:java .lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.net.Uri android.content.Intent.getData()”

【问题讨论】:

    标签: android-studio firebase camera uri


    【解决方案1】:

    尝试将mCurrentPhotoPath = image.getAbsolutePath(); 更改为mCurrentPhotoPath = "file:" + image.getAbsolutePath();。 我没有发现与我的代码有任何其他差异,这已经奏效了。

    【讨论】:

    • 不,不幸的是,这个小调整并没有奏效。也许是别的东西?如果您可以再次检查,或者您想查看其他文件?
    • 你处理过相机权限吗?很可能需要运行时权限请求,我只是通过在虚拟设备设置中启用相机权限来测试它。
    • 互联网,READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE,相机。我有这些权限,它成功打开相机,我可以拍照。问题似乎是 Uri 没有拍摄图像,因此我可以将其上传到 Firebase。
    • 我的主要 XML - codeshare.io/5RArW2 我的 MainActivity Java - codeshare.io/aYBrnG 我刚刚对其进行了测试,我的示例仍然适用于我。请检查代码,看看您是否遗漏了什么。它有两个按钮,一个用于从图库中提取,另一个用于用相机拍照。然后将其上传到 Firebase 并在 ImageView 中显示。当然,您需要使用 Firebase 设置您的应用程序。如果您发现您的代码有问题,请分享。
    • 非常感谢!我发现了错误,太笨了:(我忘了把 photoURI 添加到 filepath.putFile(photoURI) 中,它只是 filepath.putFile(uri) - 难怪它像以前一样崩溃了。
    【解决方案2】:

    所以答案很简单,感谢 cmets 中的@wilkas 帮助。我只是忘了将 photoURI 添加到 filepath.putFile(photoURI) 中,它只是 filepath.putFile(uri),所以在我注意到这一点之前,添加的代码什么也没做。希望这个问答能帮助其他有类似问题的人!

    【讨论】:

      猜你喜欢
      • 2014-01-18
      • 1970-01-01
      • 2018-03-14
      • 2017-08-18
      • 2017-10-01
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      相关资源
      最近更新 更多