'How to fix NullPointerException: uri
I am building an Android application and starting to learn to save the images. What I am trying to do is saving bitmap to a folder in DCIM, so I am calling the function save Image and passing the bitmap.However when I try to save it, the app crash with the error.
Calling the function
saveImage(bitmap,"Face");
The saveImage function
private void saveImage(Bitmap bitmap, @NonNull String name) throws IOException {
boolean saved;
OutputStream fos;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentResolver resolver = getApplicationContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "DCIM/" + IMAGES_FOLDER_NAME);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
fos = resolver.openOutputStream(imageUri);
} else {
String imagesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).toString() + File.separator + IMAGES_FOLDER_NAME;
File file = new File(imagesDir);
if (!file.exists()) {
file.mkdir();
}
File image = new File(imagesDir, name + ".png");
fos = new FileOutputStream(image);
}
saved = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Log.e("Save Image", "successfully");
}
Error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fypredo, PID: 6996
java.lang.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:133)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1488)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:1238)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:1214)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
