Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android studio 使用摄像头和;上载到Firebase(onActivityResult()中的Uri为空)_Android Studio_Firebase_Camera_Uri - Fatal编程技术网

Android studio 使用摄像头和;上载到Firebase(onActivityResult()中的Uri为空)

Android studio 使用摄像头和;上载到Firebase(onActivityResult()中的Uri为空),android-studio,firebase,camera,uri,Android Studio,Firebase,Camera,Uri,所以我有一个问题,在我之前的问题中提到过: 我对这个问题进行了更多的搜索,并应用了Android Studio文档: 因此,在您阅读代码之前,我基本上想说需要什么:我只想用相机拍摄一张照片,并将其直接上传到Firebase存储。要做到这一点,我需要Uri来包含我刚才拍摄的图片(Uri.getLastPathSegment()),但是我仍然无法成功地做到这一点 现在,我的代码是这样的(仅相关部分): AndroidManifest.xml: <provider android

所以我有一个问题,在我之前的问题中提到过:

我对这个问题进行了更多的搜索,并应用了Android Studio文档:

因此,在您阅读代码之前,我基本上想说需要什么:我只想用相机拍摄一张照片,并将其直接上传到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_path.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>
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();
            }
        });
        }
    }
}

最后是MainActivity.java

<?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>
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();
            }
        });
        }
    }
}
public类MainActivity扩展了AppCompatActivity{
私人按钮b_画廊,b_捕捉;
私人影像查看iv_影像;
私有存储参考存储;
专用静态最终int画廊\u意图=2;
专用静态最终int摄像机\u请求\u代码=1;
私有进程对话;
串电流光路;
私有文件createImageFile()引发IOException{
//创建图像文件名
字符串时间戳=新的SimpleDateFormat(“yyyyMMdd_HHmmss”)。格式(新日期();
字符串imageFileName=“JPEG_389;”+时间戳+“389;”;
File storageDir=getExternalFilesDir(Environment.DIRECTORY\u图片);
File image=File.createTempFile(
imageFileName,/*前缀*/
“.jpg”,/*后缀*/
storageDir/*目录*/
);
//保存文件:路径以用于操作\视图意图
mCurrentPhotoPath=image.getAbsolutePath();
返回图像;
}
私有无效DispatchTakePictureContent(){
Intent takePictureIntent=新的意图(MediaStore.ACTION\u IMAGE\u CAPTURE);
//确保有摄像头活动来处理意图
if(takePictureContent.resolveActivity(getPackageManager())!=null){
//创建照片应该放在哪里的文件
文件photoFile=null;
试一试{
photoFile=createImageFile();
}捕获(IOEX异常){
//创建文件时出错。。。
}
//仅当成功创建文件时才继续
if(photoFile!=null){
Uri photoURI=FileProvider.getUriForFile(这个,
“com.example.android.fileprovider”,
照片文件);
takePictureContent.putExtra(MediaStore.EXTRA_输出,photoURI);
startActivityForResult(拍摄图片内容、摄像头请求代码);
}
}
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storage=FirebaseStorage.getInstance().getReference();
b_gallery=(按钮)findViewById(R.id.b_gallery);
b_捕获=(按钮)findViewById(R.id.b_捕获);
iv_图像=(ImageView)findViewById(R.id.iv_图像);
progressDialog=新建progressDialog(此);
b_capture.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//意向意向=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
DispatchTakePictureContent();
}
});
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
if(requestCode==CAMERA\u REQUEST\u CODE&&resultCode==RESULT\u OK){
progressDialog.setMessage(“上载…”);
progressDialog.show();
Uri=data.getData();
StorageReference文件路径=storage.child(“照片”).child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(新的OnSuccessListener(){
@凌驾
成功时公共无效(UploadTask.TaskSnapshot TaskSnapshot){
Toast.makeText(MainActivity.this,“上载成功!”,Toast.LENGTH_SHORT.show();
progressDialog.disclose();
}
}).addOnFailureListener(新的OnFailureListener(){
@凌驾
public void onFailure(@NonNull异常e){
Toast.makeText(MainActivity.this,“上载失败!”,Toast.LENGTH_SHORT.show();
}
});
}
}
}
需要一个解决方案!但是,在我拍照并按下确认按钮后,应用程序崩溃,我得到以下崩溃报告:

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


尝试更改
mCurrentPhotoPath=image.getAbsolutePath()
to
mCurrentPhotoPath=“文件:”+image.getAbsolutePath()
我没有发现我的代码与我的代码有任何其他差异,因为我的代码已经起作用了。

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

不,不幸的是,这个小小的调整没有起作用。也许是别的原因?如果您可以再次检查,或者您想查看其他一些文件?您是否处理了摄像头权限?很可能需要运行时权限请求,我只是通过在虚拟设备设置中启用摄像头权限来测试它。INTERNET、读取外部存储、写入外部存储、摄像头。我有这些权限,它成功地打开相机,我可以拍照。问题似乎是Uri没有获取图像,因此我可以将其上载到Firebase