1

I am trying to store my bitmap images into a jpeg file in the Items directory. However when trying to compress the bitmap into a JPEG using the compress () I receive a null pointer exception. I have tried debugging and have found that the Items directory I try to create fails, therefore no directory is created. Also, the bitmap is not 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. 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.

Code that tries to save bitmap to the Items directory:

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:

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) 
  • `Caused by: java.lang.NullPointerException at android.graphics.Bitmap.compress(Bitmap.java:1407)` You have not bitmap.compress(....); but null.compress(....); as yyou have no bitmap. Its value is null. – blackapps Aug 31 '20 at 18:48
  • `catch (FileNotFoundException e) { e.printStackTrace (); }` If there is suchh an exception you continu as if noting has happened. Better `catch (FileNotFoundException e) { e.printStackTrace (); Toast ( .......); return; }` – blackapps Aug 31 '20 at 18:53
  • `if (!dirCreated) { Log.d ("notCreated", "the directory has failed");` You continue as if nothng has happened. Better: `if (!dirCreated) { Log.d ("notCreated", "the directory has failed"); Toast (.....); return;} ` – blackapps Aug 31 '20 at 18:56
  • `Log.d ("filey", "file has been created");//I receive this in the log cat` I do believe that but you cannot say that here as the file is not yet created. This will only be created by new FileOutputStream() so update your code. Also add all the Toasts and returns i proposed. – blackapps Aug 31 '20 at 19:00
  • `I now have been able to create the Items directory ` How did yo do that? With the posted code? Or how? Using a file Manager? Does not bring you further. Your app should create that directory. – blackapps Aug 31 '20 at 19:04
  • I think outputStream==null. And on an Android 10 device you cannot use Environment.getExternalStorageDirectory () – blackapps Aug 31 '20 at 19:05

2 Answers2

0

Check to make sure outputStream is not null, compress() will throw a NullPointerException() if the output stream is null.

Rich
  • 261
  • 1
  • 7
-1

as i see in Null Pointer Exception when trying to compress Bitmap you need to make something like this:

Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(outputStream .toByteArray()));
CLAIN Cyril
  • 123
  • 9