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

我有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); } } } 

在这个class上有:

 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前期设备中崩溃。

Solutions Collecting From Web of "由java.lang.NullPointerException引发:尝试调用空对象引用的虚拟方法'int android.graphics.Bitmap.getWidth()'"

你面临的问题是,你正在尝试getWidth()在你的unscaledBitmapcreateScaledBitmap函数。 显然,你的unscaledBitmap有时是null 。 并调用getWidth()导致空指针exception。

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

原因可以包括 –

  1. 没有读取权限
  2. 图像文件已损坏
  3. 没有足够的内存来解码文件
  4. 资源不存在
  5. optionsvariables中指定的选项无效。

我build议你修改你的代码,在解码的位图上包含一个空值检查,logging下来,并从那里看到发生错误的特定设备上进行debugging。

也可能是您正在重新使用的选项variables在对decodeResource的第二次调用中的解释不同。 你可以尝试在那里传递null。

修改后的代码应该如下 –

 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; } } 

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

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

  1. 缺lessAndroidManifest.xml中的权限。 读或写权限。
  2. 该文件不存在,或者您尝试访问不能被解码为位图的文件。

从你发布的代码,我找不到任何逻辑错误。这里是我的build议:

  1. 改变另一个图像和testing。

  2. 尝试使用像Glide或Fresco ImageLoader图书馆和testing。