由java.lang.NullPointerException引起:尝试在空对象引用上调用虚方法'int android.graphics.Bitmap.getWidth()'

时间:2016-11-06 13:46:41

标签: android android-activity nullpointerexception android-bitmap

我有BitmapScalingHelper.java:

public class BitmapScalingHelper
{
    public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight)
    {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inJustDecodeBounds = false;

        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight);

        Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options);

        return unscaledBitmap;
    }

    public static Bitmap decodeFile(String filePath, int dstWidth, int dstHeight)
    {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight);

        Bitmap unscaledBitmap = BitmapFactory.decodeFile(filePath, options);

        return unscaledBitmap;
    }


    public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight)
    {
        final float srcAspect = (float)srcWidth / (float)srcHeight;
        final float dstAspect = (float)dstWidth / (float)dstHeight;

        if (srcAspect > dstAspect)
        {
            return srcWidth / dstWidth;
        }
        else
        {
            return srcHeight / dstHeight;
        }
    }

    public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight)
    {
        Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight());

        Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight);

        Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
                Config.ARGB_8888);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));

        return scaledBitmap;
    }

    public static Rect calculateSrcRect(int srcWidth, int srcHeight)
    {
        System.out.print("Scr" + srcWidth + " " + srcHeight);
        return new Rect(0, 0, srcWidth, srcHeight);
    }

    public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight)
    {
        final float srcAspect = (float)srcWidth / (float)srcHeight;
        final float dstAspect = (float)dstWidth / (float)dstHeight;

        if (srcAspect > dstAspect)
        {
            return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect));
        }
        else
        {
            return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight);
        }
    }
}

在本课程中有:

createScaledBitmap()

...返回缩放的位图图像。

在另一堂课中,我有这个方法:

public Bitmap readSelectedBitmapFromFile(Context context, String fileName)
    {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);

        Bitmap scaledBitmap = getDefaultBitmap(context);

        try {
            File themeParentDir = context.getDir(THEME_DIRECTORY_NAME, Context.MODE_PRIVATE); //Creating an internal dir;
            File themeSubDir = new File(themeParentDir, THEME_SUB_DIRECTORY_NAME + getThemeBasedDirectoryNumber(m_SelectedTheme));
            themeSubDir.mkdir();

            File themeFileWithinDir = new File(themeSubDir, fileName); //Getting a file within the dir.

            if(themeFileWithinDir.exists())
            {
                // Part 1: Decode image
                Bitmap unscaledBitmap = BitmapScalingHelper.decodeFile(themeFileWithinDir.getPath(), metrics.widthPixels, metrics.heightPixels);

                // Part 2: Scale image
                scaledBitmap = BitmapScalingHelper.createScaledBitmap(unscaledBitmap, metrics.widthPixels, metrics.heightPixels);
                unscaledBitmap.recycle();
            }

            m_SelectedBitmap = scaledBitmap;

        }
        catch (Error e) {
            e.printStackTrace();
        }

        return scaledBitmap;
    }

此代码在许多设备上运行良好。但它在某些设备上崩溃了。任何人都可以帮帮我吗?

我收到这样的日志:

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
       at android.app.ActivityThread.access$1100(ActivityThread.java:222)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:158)
       at android.app.ActivityThread.main(ActivityThread.java:7229)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
       at in.plackal.lovecyclesfree.util.BitmapScalingHelper.createScaledBitmap(SourceFile:62)
       at in.plackal.lovecyclesfree.general.ThemeManager.readSelectedBitmapFromFile(SourceFile:202)
       at in.plackal.lovecyclesfree.activity.SplashActivity.onCreate(SourceFile:70)
       at android.app.Activity.performCreate(Activity.java:6876)
       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
       at android.app.ActivityThread.access$1100(ActivityThread.java:222)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:158)
       at android.app.ActivityThread.main(ActivityThread.java:7229)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

如果是权限问题,它不应该在Android-M版本之下崩溃,但它也会在某些Android-M之前的设备中崩溃。

7 个答案:

答案 0 :(得分:7)

您遇到的问题是,您正试图在getWidth()功能unscaledBitmapcreateScaledBitmap unscaledBitmap。显然,您的null有时是getWidth();并且调用decodeResource导致空指针异常。

根本原因是decodeResource因任何原因返回null。

原因可包括 -

  1. 没有读取权限
  2. 图像文件已损坏
  3. 没有足够的内存来解码文件
  4. 资源不存在
  5. 选项变量中指定的选项无效。
  6. 我建议你修改你的代码,在解码后的位图上包含空值,然后在你看到错误发生的特定设备上进行记录和调试。

    您可能正在重复使用的选项变量在第二次调用public class BitmapScalingHelper { public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight) { Options options = new Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); options.inJustDecodeBounds = false; options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight); options = new Options(); //May use null here as well. The funciton may interpret the pre-used options variable in ways hard to tell. Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options); if(unscaledBitmap == null) { Log.e("ERR","Failed to decode resource - " + resId + " " + res.toString()); return null; } return unscaledBitmap; } } 时的解释方式不同。您可以尝试在那里传递null。

    修改后的代码应如下 -

    var value = new Tuple<string, string>();
    
    // later...
    
    value.Item1 = "a string";
    value.Item2 = "another string";
    

答案 1 :(得分:1)

对于 Android 10 ,将此行添加到清单:

android:requestLegacyExternalStorage="true"

请注意,您还必须添加所需的权限:

READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE

enter image description here

答案 2 :(得分:0)

您正在使用:Bitmap decodeFile (String pathName) 如果文件的解码失败,则此方法可能返回null。 我认为它可能与某些设备上的权限问题或不支持的图像格式有关。 如果您使用的是GIF,请尝试https://developer.android.com/reference/android/graphics/Movie.html

答案 3 :(得分:0)

有一些原因可能会导致错误。

  1. AndroidManifest.xml中缺少权限。读或写权限。
  2. 该文件不存在或您尝试访问无法解码为位图的文件。
  3. 从您发布的代码中,我找不到任何逻辑错误。这是我的建议:

    1. 更改另一张图片并进行测试。

    2. 尝试使用像Glide或Fresco这样的ImageLoader库并进行测试。

答案 4 :(得分:0)

如果您使用的库jar创建不当,并且在gradle上将minifyEnabled设置为true,也会导致此错误。

答案 5 :(得分:0)

简单答案: 请按照以下步骤操作。.

  1. 长按已安装的APP图标。
  2. 转到“应用信息”部分。
  3. 现在单击“应用程序许可”部分
  4. 启用存储权限

现在它可以正常工作

enter image description here

enter image description here

答案 6 :(得分:0)

好吧,我反复遇到此错误,针对此问题的解决方法是确保您使用.png图像作为位图图像并将其保存在drawable文件夹中。以前,我将其用作向量资产。 这对我来说很好。