java.lang.RuntimeException:无法交付结果ResultInfo {who = null,request = 1,result = -1,data = Intent {}}

时间:2018-09-21 10:13:08

标签: android

我只想从相机拍摄照片并将其设置为ImageView。我关注了developer.android上的文档。当我单击按钮时,当我捕获图像并标记为“确定”时,它会在模拟器上打开仿真

  

进程:projectname.glob.projectname,PID:11771                                                                                      java.lang.RuntimeException:无法将结果ResultInfo {who = null,request = 1,result = -1,data = Intent {}}传递到活动{projectname.glob.projectname / projectname.glob.projectname.MainActivity}:Java。 lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.Object android.os.Bundle.get(java.lang.String)'                                                                                          在android.app.ActivityThread.deliverResults(ActivityThread.java:4323)                                                                                          在android.app.ActivityThread.handleSendResult(ActivityThread.java:4366)                                                                                          在android.app.ActivityThread.-wrap19(未知来源:0)                                                                                          在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1649)                                                                                          在android.os.Handler.dispatchMessage(Handler.java:105)                                                                                          在android.os.Looper.loop(Looper.java:164)                                                                                          在android.app.ActivityThread.main(ActivityThread.java:6540)                                                                                          在java.lang.reflect.Method.invoke(本机方法)                                                                                          在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:240)                                                                                          在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)                                                                                       原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.Object android.os.Bundle.get(java.lang.String)'                                                                                          在projectname.becse.kit.projectname.MainActivity.onActivityResult(MainActivity.java:91)                                                                                          在android.app.Activity.dispatchActivityResult(Activity.java:7237)                                                                                          在android.app.ActivityThread.deliverResults(ActivityThread.java:4319)

我的代码: MainActivity

    package projectname.glob.projectname;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity {

    String mCurrentPhotoPath;

    static final int REQUEST_TAKE_PHOTO = 1;
    ImageView mImageView;
    Button btn_takePhoto;
    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_SMS};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_layout);
        mImageView=(ImageView)findViewById(R.id.imgv);
        btn_takePhoto=(Button)findViewById(R.id.btn_takePhoto);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(arePermissionsEnabled()){
                Toast.makeText(MainActivity.this,"All Permission Granted",Toast.LENGTH_LONG).show();
            }else{
                requestMultiplePermissions();
            }
        }

        btn_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dispatchTakePictureIntent();

            }
        });

    }

    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
                Toast.makeText(MainActivity.this,"Device Not Able To Create File",Toast.LENGTH_LONG).show();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "projectname.glob.projectname.MainActivity",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && data!=null) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }
    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;
    }


    /*********************Permission Releted Work**************************/
    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean arePermissionsEnabled(){
        for(String permission : permissions){
            if(checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
                return false;
        }
        return true;
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestMultiplePermissions(){
        List<String> remainingPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                remainingPermissions.add(permission);
            }
        }
        requestPermissions(remainingPermissions.toArray(new String[remainingPermissions.size()]), 101);
    }
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 101){
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                    if(shouldShowRequestPermissionRationale(permissions[i])){
                        new AlertDialog.Builder(this)
                                .setMessage("We are taking some permisson just to access data locally ")
                                .setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        requestMultiplePermissions();
                                    }
                                })
                                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .create()
                                .show();
                    }
                    return;
                }
            }
            //all is good, continue flow
        }
    }
    /*********************Permission Releted Work**************************/
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="projectname.glob.projectname">

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="projectname.glob.projectname.MainActivity"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我在哪里定义路径的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/projectname.glob.projectname/files/Pictures" />
</paths>

可能存在一些愚蠢的错误,但我无法弄清楚!

1 个答案:

答案 0 :(得分:0)

Bundle bundle = getIntent().getExtras();
if (bundle != null)
{
     Bitmap imageBitmap = (Bitmap) extras.get("data");
     mImageView.setImageBitmap(imageBitmap);
}