简体   繁体   English

NullPointerException:尝试获取具有正确权限的空数组的长度

[英]NullPointerException: Attempt to get length of null array with right permissions

I make this app for school and need to hand it in tomorrow. 我为学校制作了该应用,明天需要交。 Little problem, it keeps crashing at a certain point. 没什么问题,它总是在某个时刻崩溃。

My app downloads a .zip from Firebase and unzips it: 我的应用程序从Firebase下载.zip并将其解压缩:

-- Cache directory -缓存目录

 --images
     --image01.jpg
     --image02.jpg
     --image03.jpg
     --and so on...
 --info.txt
 --scan234702640.zip // this is the file that includes the /images and the info.txt

So I have the following code in my class imageHandler: 所以我的类imageHandler中有以下代码:

// Get the file
    gsReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

            String path = "";
            File f = new File(context.getExternalCacheDir().toURI());
            File[] files1 = f.listFiles();
            for (File inFile1 : files1) {
                if (inFile1.getName().contains("scan")) {
                    path = context.getExternalCacheDir() + "/" +  inFile1.getName();
                }
            }

            //Decompress zip and build bitmap array
            try {
                ZipFile zip = new ZipFile(path);
                zip.extractAll(context.getExternalCacheDir() + "/");
            } catch (ZipException e){
                Toast.makeText(context, "ZIP error " + e.getCode() + " : " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            //Construct bitmap array
            ArrayList<Bitmap> pictures = new ArrayList<Bitmap>();
            File f3 = new File(context.getExternalCacheDir().toString() + "/images/");
            if (f3.exists()) {
                File[] files3 = f3.listFiles(); //THE PROBLEM IS SOMEWHERE HERE

                if (files3 != null) {
                    for (File inFile3 : files3) {
                        if (inFile3.exists()) {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                            Bitmap bitmap = BitmapFactory.decodeFile(inFile3.getPath(), options);
                            pictures.add(bitmap);
                        }
                    }
                }
            }

            // DEBUG: Show what we have in our cache location

            String message = "";
            File f2 = new File(context.getExternalCacheDir().toURI() + "/images");
            File[] files2 = f2.listFiles();
            for (File inFile2 : files2) {
                if (inFile2.isDirectory()) {
                    message += "/" + inFile2.getName() + "\n";
                } else {
                    message += inFile2.getName() + "\n";
                }
            }

            AlertDialog dialog = new AlertDialog.Builder(context)
                    .setTitle("Test Message")
                    .setMessage(message)
                    .show();

            // END OF DEBUG


        }
    });

    return scan;

So, it crashes at the part where it says "THE PROBLEM IS SOMEWHERE HERE". 因此,它在显示“问题在何处”的部分崩溃。 I have asked all EXTERNAL_STORAGE permissions and I've checked if the files exist. 我已经询问了所有EXTERNAL_STORAGE权限,并检查了文件是否存在。 I found out, in debug mode, that it successfully adds the bitmaps to the array, but when I have for example 10 images, it crashes after it loaded all 10 in. So pls help me ;) 我发现,在调试模式下,它成功地将位图添加到了数组中,但是例如当我有10张图像时,在全部加载10张图像后它便崩溃了。请帮我;)

Thx a lot, Jules 非常感谢,朱尔斯

EDIT Here is the console log: 编辑这是控制台日志:

10-31 00:07:31.060 7536-7536/com.julescitronic.meeting E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.julescitronic.meeting, PID: 7536
                                                                     java.lang.NullPointerException: Attempt to get length of null array
                                                                         at com.julescitronic.meeting.imageHandler$2.onSuccess(imageHandler.java:152)
                                                                         at com.julescitronic.meeting.imageHandler$2.onSuccess(imageHandler.java:127)
                                                                         at com.google.firebase.storage.StorageTask$1.zza(Unknown Source:9)
                                                                         at com.google.firebase.storage.StorageTask$1.zzl(Unknown Source:4)
                                                                         at com.google.firebase.storage.zze$2.run(Unknown Source:10)
                                                                         at android.os.Handler.handleCallback(Handler.java:789)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                         at android.os.Looper.loop(Looper.java:164)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

I have the same problem. 我也有同样的问题。 Use this insted of Bitmap to load pictures because loading pictures by Bitmap takes a lot of memory and crash your app 使用 Bitmap来加载图片,因为按位图加载图片会占用大量内存,并使您的应用崩溃

I found out, in debug mode, that it successfully adds the bitmaps to the array, but when I have for example 10 images, it crashes after it loaded all 10 in. 我发现,在调试模式下,它可以将位图成功添加到数组中,但是当我有10张图像时,在全部加载10张图像后它就会崩溃。

Based on your last sentence, I believe that you have memory issues rather than permission issues. 根据您的最后一句话,我认为您遇到的是内存问题,而不是权限问题。

 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
 Bitmap bitmap = BitmapFactory.decodeFile(inFile3.getPath(), options);
 pictures.add(bitmap);

With this code you load each bitmap in its full size and add it to a list of bitmaps, depriving GC to free the native object associated with the bitmap. 使用此代码,您可以按原样加载每个位图并将其添加到位图列表中,从而剥夺了GC释放与该位图关联的本机对象的权限。 This can be a big problem if you load an image with let's say 10 MB * 10 images. 如果加载的图像大小为10 MB * 10张图像,这可能是一个大问题。 That will easily lead to memory issues. 这很容易导致内存问题。

I would suggest to load the bitmaps more efficiently. 我建议更有效地加载位图。 This would mean, that you load a downsampled bitmap into memory and use that one, since having a Bitmap with size for example 3000x4000 makes no sense if it will be displayed on an ImageView with size 512x384. 这将意味着您将降采样的位图加载到内存中并使用该位图,因为如果位图的大小例如为3000x4000,则将其显示在尺寸为512x384的ImageView上是没有意义的。 This link is a good guide and can be of help: 该链接是一个很好的指南,可以为您提供帮助:

https://developer.android.com/topic/performance/graphics/load-bitmap.html https://developer.android.com/topic/performance/graphics/load-bitmap.html

listFiles();

is a file permission, I was getting similar crash in my code on Android API 23 and above (as file storage permission is required during runtime), so I provided same as follow : 是文件权限,我在Android API 23及更高版本上的代码中遇到了类似的崩溃(因为在运行时需要文件存储权限),所以我提供了以下内容:

if (Build.VERSION.SDK_INT >= 23) {
            if (AppMain.mContext.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG, "Permission is granted");
                return true;
            } else {
                ActivityCompat.requestPermissions(activityContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }

After this I didn't get null pointer on listFile operation. 之后,我没有在listFile操作上得到空指针。

暂无
暂无

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

相关问题 Android java.lang.NullPointerException:尝试获取空数组的长度 - Android java.lang.NullPointerException: Attempt to get length of null array java.lang.NullPointerException:尝试获取与“无法读取空数组”相关的空数组的长度 - java.lang.NullPointerException: Attempt to get length of null array related with 'can't read null array' 为什么google map v2突然崩溃了java.lang.NullPointerException:尝试获取null数组的长度? - Why google map v2 suddenly crashed by java.lang.NullPointerException: Attempt to get length of null array? 获取 java.lang.NullPointerException: Attempt to get length of null array 错误 - Getting java.lang.NullPointerException: Attempt to get length of null array error 谷歌地图 api 获得致命异常:java.lang.NullPointerException:尝试获取 null 数组的长度 - Google maps api gets Fatal Exception: java.lang.NullPointerException: Attempt to get length of null array 尝试获取空数组 Kotlin 的长度 - Attempt to get length of null array Kotlin 尝试获取file.Length()的空数组的长度 - Attempt to get Length of null Array of file.Length() 尝试在 NfcManager.start() 上获取空数组的长度 - Attempt to get length of null array on NfcManager.start() 如何解决我的 logcat 中尝试获取 null 数组长度的问题? - how to solve the Attempt to get length of null array problem in my logcat? 编码pdf文件时尝试获取空数组的长度 - Attempt to get length of null array when encode pdf file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM