Skip to content
Advertisement

Null Pointer Exception when Compressing a Bitmap created from layout [closed]

I am trying to make an image from the layout and download it. I am downloading this as a test to make sure the image is correct before I attempt to then convert the bitmap to PDF for download.

I am receiving a null pointer exception, and I am having issues trying to fix this issue.

 Bitmap bitmap = Bitmap.createBitmap(relativeLayout.getWidth(), relativeLayout.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                relativeLayout.draw(canvas);

                File filepath = Environment.getExternalStorageDirectory();
                File dir = new File(filepath.getAbsolutePath() + "/Demo/");
                dir.mkdir();
                File file = new File(dir, System.currentTimeMillis() + ".jpg");

                try {
                    outputStream = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                bitmap.compress(Bitmap.CompressFormat.JPEG, 0, outputStream);

                try {
                    outputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

Advertisement

Answer

 File file = new File(dir, System.currentTimeMillis() + ".jpg");

You declared File here, but did not create it

try file.createNewFile()

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement