编程语言
首页 > 编程语言> > 上传图片错误:尝试在空对象引用上调用虚拟方法’java.lang.String android.net.Uri.getLastPathSegment()’

上传图片错误:尝试在空对象引用上调用虚拟方法’java.lang.String android.net.Uri.getLastPathSegment()’

作者:互联网

我有“用相机捕获图像”的问题,并将其存储到Firebase中.我认为该代码是正确的,因为它可以与“从图库中选择图像”一起使用.捕获完图像后,该应用程序停止了,并且没有存储在数据库中.我认为这对于android M和N是个问题.我只是看到其他类似的问题,但它们对我不起作用.我为此寻求帮助,因为我不知道解决方案.谢谢. logcat中也存在错误.

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


    if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
        mPregresDialog.setMessage("Uploading...");
        mPregresDialog.show();

        Uri uri = data.getData();
        StorageReference filepath = mStorage.child("Photo").child(uri.getLastPathSegment());
        filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                mPregresDialog.dismiss();

                Toast.makeText(MainActivity.this, "Upload Done", Toast.LENGTH_LONG).show();

            }
        });

    }}

日志猫:

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

解决方法:

对于您的问题,我有一个答案,因为几天前我做了同样的事情.问题在于您的Uri无法获得应有的图像,因此您需要为捕获的图像创建自己的Uri.

您需要转到android文档:https://developer.android.com/training/camera/photobasics.html#TaskPhotoView

对于您的应用,您还可以将以下代码复制并粘贴到您的主要活动中:

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

并确保您遵循文档并在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(您只需在“ 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>

确保将com.serjardovic.firebasesandbox更改为您自己的包名称!

效果100%-玩得开心!

标签:firebase,camera,firebase-storage,android,image-uploading
来源: https://codeday.me/bug/20191026/1937019.html