简体   繁体   English

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean java.io.File.exists()”

[英]java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.exists()' on a null object reference

Hello everyone, I try to access the storage and select an image immediately after the app crashes me and then I get the following error:大家好,我尝试在应用程序崩溃后立即访问存储并选择图像,然后出现以下错误:

It is important to note API 29 everything works great and only when I upload the API to version 30-31 I get this error.重要的是要注意 API 29 一切正常,只有当我将 API 上传到版本 30-31 时才会收到此错误。 I have all the storage permissions我拥有所有存储权限

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pets.igloopet, PID: 9797
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.io.File.exists()' on a null object reference
    at com.pets.igloopet.activity.addpet.AddImage$1.onClick(AddImage.java:149)
    at com.cocosw.bottomsheet.BottomSheet$4.onItemClick(BottomSheet.java:332)
    at android.widget.AdapterView.performItemClick(AdapterView.java:330)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1197)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3190)
    at android.widget.AbsListView$3.run(AbsListView.java:4166)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:201)
    at android.os.Looper.loop(Looper.java:288)
    at android.app.ActivityThread.main(ActivityThread.java:7839)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

This is my code (File Addimage.java):这是我的代码(文件 Addimage.java):

        builder.listener(new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case R.id.camera_cards:
                    if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
                        if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            try {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File file = getOutputMediaFile(1);
                               
                                if (!file.exists()) {
                                    try {
                                        ProjectUtils.pauseProgressDialog();
                                        file.createNewFile();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    //Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.asd", newFile);
                                    picUri = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getApplicationContext().getPackageName() + ".fileprovider", file);
                                } else {
                                    picUri = Uri.fromFile(file); // create
                                }

                                sharedPrefrence.setValue(Consts.IMAGE_URI_CAMERA, picUri.toString());
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri); // set the image file
                                startActivityForResult(intent, PICK_FROM_CAMERA);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    break;
                case R.id.gallery_cards:
                    if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_CAMERA, Manifest.permission.CAMERA)) {
                        if (ProjectUtils.hasPermissionInManifest(getActivity(), PICK_FROM_GALLERY, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {


                         File file = getOutputMediaFile(1);

                            if (!file.exists()) {

                                try {
                                    file.createNewFile();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }


                            picUri = Uri.fromFile(file);

                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);

                        }
                    }
                    break;
                case R.id.cancel_cards:
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            dialog.dismiss();
                        }
                    });
                    break;
            }
        }
    });

You have horrible error and null handling.你有可怕的错误和空处理。 Things go wrong?事情出错了? Sod it, log nothing, do nothing, just return null !草皮,什么都不记录,什么都不做,只返回null

And now you are wondering why you get unexpected null pointer exceptions.现在您想知道为什么会出现意外的空指针异常。

As homer would say, 'Duh'.正如荷马所说,“呃”。

We can delve into why it happens here specifically but this is interchangible with a thousand other similar situations.我们可以深入研究为什么它会特别发生在这里,但这可以与其他一千种类似情况互换。 The real fix is for you to stop handling errors like this.真正的解决方法是让您停止处理这样的错误。

Here's an example:这是一个例子:

 if (!mediaStorageDir.mkdirs()) { return null; }

This is silly.这很愚蠢。 Don't do this.不要这样做。 And it would directly lead to your NPE error here if indeed making the directories fails to work.如果确实使目录无法正常工作,它将直接导致您的 NPE 错误。

Log something if you want, but most of all, when things occur that you did not expect, and you don't quite now what it means if it happens, always throw an exception , and add details if you like.如果你想记录一些东西,但最重要的是,当你没有预料到的事情发生时,并且你现在不太清楚如果它发生意味着什么,总是抛出一个异常,如果你愿意,可以添加细节。 The exception means that IF the unexpected happens, at least you get a stack trace with a whole bunch of details and crucially, something pointing right at the place where the weird, unexpected, not quite understood thing happened.异常意味着如果发生意外,至少你会得到一个堆栈跟踪,其中包含一大堆细节,而且至关重要的是,一些东西指向了奇怪的、意外的、不太理解的事情发生的地方。 It would in this case be pointing right at "Weird, I can't make those dirs" - at least now you know what to investigate.在这种情况下,它会指向“奇怪,我无法制作那些目录”——至少现在你知道要调查什么了。 Perhaps your app doesn't have the appropriate file rights, android will just fail the operation if your app doesn't have the user permission.也许您的应用没有适当的文件权限,如果您的应用没有用户权限,android 只会导致操作失败。

You pull the same stunt when type isn't 1 - then you just go: Oh, uh, no idea, whatever - just return null.type不是1时,你会使用同样的噱头——然后你就走了:哦,呃,不知道,无论如何——只返回 null。 Don't.不。 That return null;return null; in the else block there should be throw new IllegalArgumentException("Type " + type + " not implemented yet");在 else 块中应该有throw new IllegalArgumentException("Type " + type + " not implemented yet"); or whatnot.什么的。

Fix those things - and then the answer to your question will become self evident.解决这些问题——然后你的问题的答案就会变得不言而喻。 Without fixing this - we don't know either.如果不解决这个问题 - 我们也不知道。

you get this exception because the method "getOutputMediaFile" return null and you try to use null object.您会收到此异常,因为“getOutputMediaFile”方法返回 null 并且您尝试使用 null 对象。

first, add null check to file, its always good approach.首先,向文件添加空检查,这总是好的方法。

second, you have to understand why this method return null and not the file you want.其次,您必须了解为什么此方法返回 null 而不是您想要的文件。 if you try to use "getExternalStorageDirectory" and call mkdirs(), its depracated, you should use "getExternalFilesDir" on your context/activity.如果您尝试使用“getExternalStorageDirectory”并调用 mkdirs(),它已被弃用,您应该在您的上下文/活动中使用“getExternalFilesDir”。

try to do the change, if it does not help, please share with us the method "getOutputMediaFile" so we can see whats going on there and give you further help.尝试进行更改,如果没有帮助,请与我们分享方法“getOutputMediaFile”,以便我们查看那里发生的情况并为您提供进一步的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 引起:java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference - Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int java.io.InputStream.read(byte[])” - java.lang.NullPointerException: Attempt to invoke virtual method 'int java.io.InputStream.read(byte[])' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean android.graphics.Bitmap.isRecycled()” - java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚方法,而它不为空 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference, while its not null java.lang.NullPointerException:尝试在 oncreate 方法中对空对象引用调用虚拟方法 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference in oncreate method java.lang.NullPointerException:尝试对空对象引用调用虚拟方法。 应用程序在运行时崩溃 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference. App crashes on run Android Studio:java.lang.NullPointerException:尝试在空对象引用[TextView]上调用虚拟方法 - Android Studio: java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference [TextView] java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法FloatingActionButton.setImageResource(int)' - java.lang.NullPointerException: Attempt to invoke virtual method FloatingActionButton.setImageResource(int)' on a null object reference java.lang.NullPointerException:尝试在 null 上调用虚拟方法 - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference Retrofit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM