当前位置: 首页 > 知识库问答 >
问题:

由java引起的。lang.NullPointerException:尝试调用虚拟方法“int android”。图样位图。空对象引用上的getWidth()

刘博文
2023-03-14

我有BitmapScalingHelper。爪哇:

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之前的设备上也会崩溃。

共有3个答案

梁马鲁
2023-03-14

简单的回答:遵循以下步骤...

  1. 长按“已安装的应用程序”图标

现在它工作正常了

在此处输入图像描述

在此处输入图像描述

何晗昱
2023-03-14

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

android:requestLegacyExternalStorage="true"

请注意,您还必须添加所需的参数:

读外部存储器,写外部存储器

利永年
2023-03-14

您所面临的问题是,您正在尝试createScaledBitmap函数中的uncaledBitmap上的getWidth()。显然,您的uncaledBitmap有时是null;并且调用getWidth()会导致空指针异常。

根本原因是无论出于何种原因,decodeResource都会返回空值。

原因可能包括-

  1. 无阅读权限

我建议您修改代码,在解码后的位图上包含一个空检查,记录它,然后在您看到错误发生的特定设备上进行调试。

也可能是您正在重新使用的选项变量在第二次调用解码资源时被不同地解释。您可以尝试在那里传递一个空值。

修改后的代码应该如下-

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;
    }
}
 类似资料:
  • 我正在尝试实现一个外部色轮,它应该出现在的片段一直在崩溃我的应用程序。我想我明白为什么会发生这种情况,但是在尝试修复它大约6个小时后,我就要放弃了。我知道之前有人问过这个问题,但是我无法为我的特定问题导出一个修复程序。下面是我的代码: 这是Logcat错误: 如果有人能帮我解决这个问题,那就太好了。提前谢谢^^ 编辑:这是我的XML,按要求:

  • 我的应用程序有问题,我想解决它,但我无法访问解决方案,请帮助我,,,

  • 问题内容: 我收到以下错误 尝试在空对象引用上调用虚拟方法’void android.widget.StackView.setAdapter(android.widget.Adapter)’ 在这条线上 完整的片段 EventsFragment.java 是 Stack_Adapter.java Stack_Items 问题答案: 您正在执行: 你是。返回。 你为什么用? 在哪里?您应该从正确的x

  • 我的应用程序有问题,想解决它,但我无法访问解决方案,请帮帮我,,

  • 我将使用库,并尝试在应用程序启动时使用以下方法获取令牌。 应用程序在发布时崩溃 AndroidManifest Build.Gradle: 此外,我尝试在SharedPreferences中缓存令牌,但似乎从未调用onNewToken()。 会有什么问题?

  • 问题内容: 我尝试使用片段来打开数据库,但是,当我单击按钮开始搜索时,程序意外终止,并显示如下错误: 主片段: DBManager类: 顺便说一句,我在MainAcitivity中使用了有关DBManager的代码,并且成功了。将代码复制到上面的片段后,它失败了,该怎么办? 问题答案: 之前和之后你都做不到。 因为,您正在执行片段实例化时。该方法将始终返回null。另外,尽量不要将参考文献保留在您