java-相机“位图imageBitmap =(位图)extras.get(“数据”);”给出Nullpointer错误

java-相机“位图imageBitmap =(位图)extras.get(“数据”);”给出Nullpointer错误,第1张

概述我在这里关注相机上的Android开发人员教程:https://developer.android.comraining/camera/photobasics#java但是我在方法中出现错误onActivityResult:,java.lang.NullPointerException:Attempttoinvokevirtualmethod‘java.lang.Objectandroid.os.Bundle.get(java

我在这里关注相机上的Android开发人员教程:https://developer.android.com/training/camera/photobasics#java

但是我在方法中出现错误

onActivityResult:,java.lang.NullPointerException: Attempt to invoke
virtual method ‘java.lang.Object
androID.os.Bundle.get(java.lang.String)’ on a null object reference

这行给出了错误:

Bitmap imageBitmap = (Bitmap) extras.get("data");

当我注释掉这一行时,该应用程序将以某种方式工作:

takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

我的整个代码位于:
https://github.com/europa9/EanScannerForAndroid

MainActivity.java

package one.askit.eanscanner;import androID.Manifest;import androID.content.Intent;import androID.content.pm.PackageManager;import androID.graphics.Bitmap;import androID.icu.text.SimpleDateFormat;import androID.net.Uri;import androID.os.Build;import androID.os.Bundle;import androID.os.Environment;import androID.provIDer.MediaStore;import androID.support.v4.content.fileProvIDer;import androID.support.v7.app.AppCompatActivity;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.FrameLayout;import androID.Widget.ImageVIEw;import androID.Widget.TextVIEw;import androID.Widget.Toast;import java.io.file;import java.io.IOException;import java.util.Date;public class MainActivity extends AppCompatActivity {    static final int REQUEST_IMAGE_CAPTURE = 1;    static final int REQUEST_TAKE_PHOTO = 1;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        // Permission        checkPermissionExternalRead();        checkPermissionExternalWrite();        checkPermissionCamera();        // Listeners        Listeners();        FrameLayout frameLayoutCameraPrevIEw = findVIEwByID(R.ID.frameLayoutCameraPrevIEw);        frameLayoutCameraPrevIEw.setVisibility(VIEw.GONE);    }    /*- Check permission Read ------------------------------------------------------------------- */    // Pops up message to user for reading    private voID checkPermissionExternalRead(){        int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;        if (checkSelfPermission(androID.Manifest.permission.READ_EXTERNAL_STORAGE)                != PackageManager.PERMISSION_GRANTED) {            // Should we show an explanation?            if (shouldShowRequestPermissionRationale(                    androID.Manifest.permission.READ_EXTERNAL_STORAGE)) {                // Explain to the user why we need to read the contacts            }            requestPermissions(new String[]{androID.Manifest.permission.READ_EXTERNAL_STORAGE},                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);            // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an            // app-defined int constant that should be quite unique            return;        }    } // checkPermissionRead    /*- Check permission Write ------------------------------------------------------------------ */    // Pops up message to user for writing    private voID checkPermissionExternalWrite(){        int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)                != PackageManager.PERMISSION_GRANTED) {            // Should we show an explanation?            if (shouldShowRequestPermissionRationale(                    androID.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {                // Explain to the user why we need to read the contacts            }            requestPermissions(new String[]{androID.Manifest.permission.WRITE_EXTERNAL_STORAGE},                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);            // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an            // app-defined int constant that should be quite unique            return;        }    } // checkPermissionWrite    /*- Check permission Camera ----------------------------------------------------------------- */    public voID checkPermissionCamera(){        int MY_PERMISSIONS_REQUEST_CAMERA = 1;        if (checkSelfPermission(Manifest.permission.CAMERA)                != PackageManager.PERMISSION_GRANTED) {            // Should we show an explanation?            if (shouldShowRequestPermissionRationale(                    Manifest.permission.CAMERA)) {                // Explain to the user why we need to read the contacts            }            requestPermissions(new String[]{androID.Manifest.permission.CAMERA},                    MY_PERMISSIONS_REQUEST_CAMERA);            // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an            // app-defined int constant that should be quite unique            return;        }    } // checkPermissionInternalRead    public voID Listeners(){        button buttonScan = findVIEwByID(R.ID.buttonScan);        buttonScan.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw v) {                buttonScanClicked();            }        });    }    public voID buttonScanClicked(){        // Scan text        TextVIEw TextVIEwScan = findVIEwByID(R.ID.TextVIEwScan);        TextVIEwScan.setText("Now scanning");        // Take picture        dispatchTakePictureIntent();    }    private voID dispatchTakePictureIntent() {        Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);        String file_path = Environment.getExternalStorageDirectory().toString() +                "/" + this.getResources().getString(R.string.app_name);        file dir = new file(file_path);        if (!dir.exists())            dir.mkdirs();        // IMAGE_PATH = new file(dir, mContext.getResources().getString(R.string.app_name) + AppConstants.USER_ID + System.currentTimeMillis() + ".png");        file IMAGE_PATH = new file(dir, this.getResources().getString(R.string.app_name) + System.currentTimeMillis() + ".png");        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {            picIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvIDer.getUriForfile(this, this.getPackagename() + ".fileprovIDer", IMAGE_PATH));        }        else {            picIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromfile(IMAGE_PATH));        }        startActivityForResult(picIntent, REQUEST_TAKE_PHOTO);    }    @OverrIDe    protected voID onActivityResult(int requestCode, int resultCode, Intent data) {        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESulT_OK) {            Bundle extras = data.getExtras();            if (extras != null) {                //Do your logic                Bitmap imageBitmap = (Bitmap) extras.get("data");                ImageVIEw imageVIEwScanPrevIEw = findVIEwByID(R.ID.imageVIEwScanPrevIEw);                imageVIEwScanPrevIEw.setimageBitmap(imageBitmap);            } else {                //Do something else                Toast.makeText(this, "Its null!", Toast.LENGTH_LONG).show();            }        }    }}

activity_main.xml中

<?xml version="1.0" enCoding="utf-8"?><linearLayout    xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:app="http://schemas.androID.com/apk/res-auto"    androID:orIEntation="vertical"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent">    <FrameLayout        androID:ID="@+ID/frameLayoutCameraPrevIEw"        androID:layout_wIDth="match_parent"        androID:layout_height="match_parent"        androID:layout_weight="1" />    <ImageVIEw        androID:ID="@+ID/imageVIEwScanPrevIEw"        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        app:srcCompat="?attr/colorAccent" />    <TextVIEw        androID:ID="@+ID/TextVIEwScan"        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:text="Doint nothing"></TextVIEw>    <button        androID:ID="@+ID/buttonScan"        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:layout_gravity="center"        androID:text="Scan" /></linearLayout>

AndroIDManifest.xml中

<?xml version="1.0" enCoding="utf-8"?><manifest xmlns:androID="http://schemas.androID.com/apk/res/androID"    package="one.askit.eanscanner">    <uses-feature androID:name="androID.harDWare.camera" androID:required="true" />    <uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE" />    <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE" />    <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">        <activity androID:name=".MainActivity">            <intent-filter>                <action androID:name="androID.intent.action.MAIN" />                <category androID:name="androID.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <provIDer            androID:name="androID.support.v4.content.fileProvIDer"            androID:authoritIEs="${applicationID}.fileprovIDer"            androID:exported="false"            androID:grantUriPermissions="true">            <Meta-data                androID:name="androID.support.file_PROVIDER_PATHS"                androID:resource="@xml/file_paths" />        </provIDer>    </application></manifest>

file_paths.xml

<?xml version="1.0" enCoding="utf-8"?><paths xmlns:androID="http://schemas.androID.com/apk/res/androID">    <external-path name="images" path="."/>    <external-path name="external_files" path="."/></paths>

解决方法:

如下更改您的文件提供者

    <provIDer        androID:name="androID.support.v4.content.fileProvIDer"        androID:authoritIEs="${applicationID}.fileprovIDer"        androID:exported="false"        androID:grantUriPermissions="true">        <Meta-data            androID:name="androID.support.file_PROVIDER_PATHS"            androID:resource="@xml/file_paths" />    </provIDer>

和你的file_path.xml如下

<?xml version="1.0" enCoding="utf-8"?><paths xmlns:androID="http://schemas.androID.com/apk/res/androID">    <external-path name="images" path="."/>    <external-path name="external_files" path="."/></paths>

对于图像捕获,请使用此意图

  Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);        String file_path = Environment.getExternalStorageDirectory().toString() +                "/" + mContext.getResources().getString(R.string.app_name);        file dir = new file(file_path);        if (!dir.exists())            dir.mkdirs();       // IMAGE_PATH = new file(dir, mContext.getResources().getString(R.string.app_name) + AppConstants.USER_ID + System.currentTimeMillis() + ".png");        IMAGE_PATH = new file(dir, mContext.getResources().getString(R.string.app_name) + System.currentTimeMillis() + ".png");        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {            picIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileProvIDer.getUriForfile(mContext, mContext.getPackagename()+".fileprovIDer", IMAGE_PATH));        }        else {            picIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromfile(IMAGE_PATH));        }        ((Activity) mContext).startActivityForResult(picIntent, CAMERA_REQUEST);

在onActivityREsult内部,您需要按以下方式更改代码

@OverrIDe    protected voID onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {        super.onActivityResult(requestCode, resultCode, data);        int cropperType = 1;        if (requestCode == REQUEST_IMAGE_CAPTURE) {            switch (resultCode) {                case Activity.RESulT_OK:                     String imagePAth= Uri.fromfile(IMAGE_PATH);                GlIDeApp.with(this).load(imagePAth).diskCacheStrategy(diskCacheStrategy.ALL).skipMemoryCache(false).                        placeholder(R.drawable.default_picture).error(R.drawable.default_picture).dontAnimate().into(YOUR_IMAGEVIEW);                    break;                case Activity.RESulT_CANCELED:                    break;            }        }    } 

而且,如果要从onActivityResult获取位图,则需要引用此链接Click here

总结

以上是内存溢出为你收集整理的java-相机“位图imageBitmap =(位图)extras.get(“数据”);”给出Nullpointer错误全部内容,希望文章能够帮你解决java-相机“位图imageBitmap =(位图)extras.get(“数据”);”给出Nullpointer错误所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1093683.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存