9

Tôi có BitmapScalingHelper.java:gây ra bởi java.lang.NullPointerException: Cố gắng để gọi phương thức ảo 'int android.graphics.Bitmap.getWidth()' trên một tài liệu tham khảo đối tượng 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); 

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

Trong lớp này có là:

createScaledBitmap() 

... trả về hình ảnh bitmap được chia tỷ lệ.

Trong lớp khác, tôi có phương pháp này:

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

Mã này đã làm việc tốt trong nhiều thiết bị. Nhưng nó đã bị rơi ở một số thiết bị. Bất kỳ ai có thể vui lòng giúp tôi không?

Tôi nhận được một bản ghi như thế này:

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) 

Nếu đó là một vấn đề cho phép, nó không nên sụp đổ dưới phiên bản Android-M, nhưng nó được đâm trong một số các thiết bị Android-M trước cũng có.

+0

mà dòng gây ra ngoại lệ –

+0

@PavanBilagi bạn đã tìm thấy một giải pháp tốt hơn cho quản lý bộ nhớ, tôi thấy rằng trong một xperia xa điều này xảy ra gần như mọi lúc. nhưng nếu bạn đang ở chế độ gỡ lỗi và chờ một chút trên decodefile trước khi nhấn f9 nó hoạt động. và hoạt động tốt ở hầu hết các thiết bị khác. và tôi đang sử dụng đôi khi như bạn. –

Trả lời

4

Vấn đề bạn đang phải đối mặt là bạn đang cố gắng để getWidth() trên unscaledBitmap của bạn trong createScaledBitmap chức năng. Rõ ràng, unscaledBitmap của bạn là null đôi khi; và gọi getWidth() đang gây ra ngoại lệ Null Pointer.

Nguyên nhân gốc là decodeResource trả lại cho bạn giá trị rỗng vì bất kỳ lý do gì.

Những lý do có thể bao gồm -

  1. Không cho phép đọc
  2. Các tập tin ảnh bị hỏng
  3. Không có đủ bộ nhớ để giải mã các tập tin
  4. Tài nguyên không tồn tại
  5. không hợp lệ tùy chọn được chỉ định trong biến tùy chọn.

Tôi khuyên bạn nên sửa đổi mã của mình để bao gồm kiểm tra null trên bitmap được giải mã, ghi nhật ký và gỡ lỗi từ đó trên các thiết bị cụ thể mà bạn thấy lỗi xảy ra.

Cũng có thể là biến tùy chọn mà bạn đang sử dụng lại đang được diễn giải khác nhau trong lần gọi thứ hai tới decodeResource. Bạn có thể thử vượt qua một null ở đó.

Mã sửa đổi nên thực hiện như sau - (. Từ phương pháp không toàn bộ lớp)

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

Bạn đang sử dụng: Bitmap decodeFile (String pathName) Phương thức này có thể trả về null nếu giải mã tệp không thành công. Tôi nghĩ rằng nó có thể liên quan đến vấn đề quyền trên một số thiết bị hoặc định dạng hình ảnh không được hỗ trợ. Nếu bạn đang sử dụng GIF, hãy thử https://developer.android.com/reference/android/graphics/Movie.html

+0

nhưng nó đã bị lỗi trong kitkat (4.4.4) cũng –

+0

bạn có thể vui lòng cung cấp quyền hiển thị của mình và cách mã hóa tệp của bạn thành THEME_DIRECTORY_NAME không? –

0

Có một số lý do có thể gây ra lỗi.

  1. Thiếu quyền trong AndroidManifest.xml. Đọc hoặc viết quyền.
  2. Tệp không tồn tại hoặc bạn đang cố gắng truy cập vào tệp không thể được giải mã dưới dạng bitmap.

Từ mã bạn gửi, tôi không thể tìm thấy bất kỳ logic error.Here là gợi ý của tôi:

  1. Thay đổi một hình ảnh và thử nghiệm.

  2. Hãy thử sử dụng Thư viện ImageLoader như Glide hoặc Fresco và kiểm tra.

Các vấn đề liên quan

 Các vấn đề liên quan