[英]Why do I get a null pointer exception when compressing bitmap to JPEG?
I am trying to store my bitmap images into a jpeg file in the Items directory.我正在尝试将我的 bitmap 图像存储到 Items 目录中的 jpeg 文件中。 However when trying to compress the bitmap into a JPEG using the compress ()
I receive a null pointer exception.但是,当尝试使用compress ()
将 bitmap 压缩为 JPEG 时,我收到 null 指针异常。 I have tried debugging and have found that the Items directory I try to create fails, therefore no directory is created.我试过调试,发现我尝试创建的 Items 目录失败,因此没有创建目录。 Also, the bitmap is not null.此外,bitmap 不是 null。
I cannot seem to find the issue as to why the directory is not created & don't know if that's the reason when compressing my bitmap I get a null pointer exception.我似乎找不到关于为什么未创建目录的问题,并且不知道这是否是压缩我的 bitmap 时出现 null 指针异常的原因。 I have tried asking permission for storage but that doesn't fix the problem.我曾尝试请求存储许可,但这并不能解决问题。
Update : I now have been able to create the Items directory however I still get a null pointer exception when compressing the Bitmap.更新:我现在已经能够创建 Items 目录,但是在压缩 Bitmap 时我仍然遇到 null 指针异常。
Code that tries to save bitmap to the Items directory:尝试将 bitmap 保存到 Items 目录的代码:
public void saveBitmap () {
boolean dirCreated;
askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, STORAGE_PERMISSION_CODE);
File filePath = Environment.getExternalStorageDirectory ();
File dir = new File (filePath.getAbsolutePath() + "/Items");
if (!dir.exists ()) {
try {
dirCreated = dir.mkdir();
if (!dirCreated) {
Log.d ("notCreated", "the directory has failed");
}
} catch (SecurityException e) {
e.printStackTrace();
}
} else {
Log.d ("dirExists", "the directory already exists");//I receive this in the Log cat
}
file = new File (dir, name + ".jpg");
Log.d ("filey", "file has been created");//I receive this in the log cat
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace ();
}
if (bitmap != null) {
Log.d ("bitty", "the bimap is not null");//I receive this in the log cat
}
bitmap.compress (Bitmap.CompressFormat.JPEG, 0, outputStream);
}
Code that converts my resource into a bitmap:将我的资源转换为 bitmap 的代码:
public void convertToBitmap () {
bitmap = BitmapFactory.decodeResource(context.getResources(), resourceId);
}
Code that asks permission for storage:请求存储权限的代码:
public void askForPermission (String permission, int requestCode) {
if (isStoragePermissionGranted()) {
ActivityCompat.requestPermissions((Activity) context, new String [] {permission}, requestCode);
} else {
Toast.makeText (context, "Permission already granted", Toast.LENGTH_SHORT)
.show();
}
}
public void onRequestPermissionsResult (int requestCode, String [] permissions, int [] grantResults) {
super.onRequestPermissionsResult (requestCode, permissions, grantResults);
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Storage Permission Granted", Toast.LENGTH_SHORT);
} else {
Toast.makeText(context, "Storage Permission Denied", Toast.LENGTH_SHORT);
}
}
}
public boolean isStoragePermissionGranted () {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "permission granted", Toast.LENGTH_SHORT)
.show();
return true;
}
return false;
}
Manifest file:清单文件:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Error I receive:我收到的错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapps.myapplication/com.myapps.myapplication.grocery_item}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3374)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException
at android.graphics.Bitmap.compress(Bitmap.java:1407)
at com.myapps.myapplication.BitmapFiles.saveBitmap(BitmapFiles.java:86) //THIS IS THE LINE OF CODE CAUSING THE EXCEPTION
at com.myapps.myapplication.BitmapFiles.<init>(BitmapFiles.java:40)
at com.myapps.myapplication.MyDatabaseHelper.createBitmapFiles(MyDatabaseHelper.java:40)
at com.myapps.myapplication.MyDatabaseHelper.upgradeDatabase(MyDatabaseHelper.java:35)
at com.myapps.myapplication.MyDatabaseHelper.onUpgrade(MyDatabaseHelper.java:63)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:417)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:341)
at com.myapps.myapplication.grocery_item.accessDataBase(grocery_item.java:35)
at com.myapps.myapplication.grocery_item.onCreate(grocery_item.java:20)
at android.app.Activity.performCreate(Activity.java:7815)
at android.app.Activity.performCreate(Activity.java:7804)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3513)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2109)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Check to make sure outputStream
is not null, compress() will throw a NullPointerException() if the output stream is null.检查以确保outputStream
不是 null,如果 output stream 是 null, compress() 将抛出 NullPointerException() 。
as i see in Null Pointer Exception when trying to compress Bitmap you need to make something like this:正如我在尝试压缩 Bitmap 时在 Null 指针异常中看到的那样,您需要执行以下操作:
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(outputStream .toByteArray()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.