0

I Get this error while try to upload a photo from gallery of my app

java.lang.RuntimeException: An error occurred while executing doInBackground()

Debug Report

Process: com.app.name, PID: 1714
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$4.done(AsyncTask.java:415)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
     Caused by: java.lang.NullPointerException
        at java.io.FileInputStream.<init>(FileInputStream.java:152)
        at com.app.name.AddProductDetail$UploadImageTask.doInBackground(AddProductDetail.java:1925)
        at com.app.name.AddProductDetail$UploadImageTask.doInBackground(AddProductDetail.java:1852)

This is my code line 1925 and 1852 is point out in a code below

    FileInputStream tempStream = null;
    try {
       **LINE 1925** tempStream = new FileInputStream(newFile);
        bytesAvailable = tempStream.available();
        if (bytesAvailable > 1024000 && bitmapImage != null) {
            AppnameApplication.getResizedBitmap(bitmapImage, 1024);
            if (newFile.exists()) newFile.delete();
            FileOutputStream out = new FileOutputStream(newFile);
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        }
        tempStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Can you show me how to do it and it seem error coming from FileInputStream tempStream = null; can anyone help me please am still learning Android Studio.

More information how the code works

@Override
        protected Integer doInBackground(String... imgpath) {
            for (int i = 0; i < imageList.size(); i++) {
                if (!imageList.get(i).getType().equals(Constants.KEY_URL) && !imageList.get(i).getType().equals(Constants.TAG_ADD)) {
                    publishProgress(Math.min(i, count));

                    HttpURLConnection conn = null;
                    String response = "error";
                    DataOutputStream dos = null;
                    DataInputStream inStream = null;
                    StringBuilder builder = new StringBuilder();
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary = "*****";
                    int bytesRead, bytesAvailable, bufferSize;
                    byte[] buffer;
                    int maxBufferSize = 1 * 1024 * 1024;
                    String urlString = Constants.API_UPLOAD_IMAGE;
                    Bitmap bitmapImage = null;
                    String exsistingFileName = imageList.get(i).getImage();
                    File file = new File(exsistingFileName);
                    File newFile = null;

                    if (imageList.get(i).getPathType().equals(Constants.TAG_GALLERY)) {
                        try {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            //                        options.inSampleSize = 8;
                            bitmapImage = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

                            ExifInterface ei = new ExifInterface(file.getAbsolutePath());
                            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                                    ExifInterface.ORIENTATION_UNDEFINED);

                            switch (orientation) {

                                case ExifInterface.ORIENTATION_ROTATE_90:
                                    bitmapImage = rotateImage(bitmapImage, 90);
                                    break;

                                case ExifInterface.ORIENTATION_ROTATE_180:
                                    bitmapImage = rotateImage(bitmapImage, 180);
                                    break;

                                case ExifInterface.ORIENTATION_ROTATE_270:
                                    bitmapImage = rotateImage(bitmapImage, 270);
                                    break;

                                case ExifInterface.ORIENTATION_NORMAL:
                                default:
                                    bitmapImage = bitmapImage;
                            }
                            newFile = saveBitmapToFile(bitmapImage, file.getName());
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        newFile = new File(imageList.get(i).getImage());
                    }

                    FileInputStream tempStream = null;
                    try {
                        tempStream = new FileInputStream(newFile);
                        bytesAvailable = tempStream.available();
                        if (bytesAvailable > 1024000 && bitmapImage != null) {
                            AppnameApplication.getResizedBitmap(bitmapImage, 1024);
                            if (newFile.exists()) newFile.delete();
                            FileOutputStream out = new FileOutputStream(newFile);
                            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
                            out.flush();
                            out.close();
                        }
                        tempStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                    try {
                        refreshGallery(newFile);
                        FileInputStream fileInputStream = new FileInputStream(newFile);
                        URL url = new URL(urlString);
                        conn = (HttpURLConnection) url.openConnection();
                        conn.setDoInput(true);
                        conn.setDoOutput(true);
                        conn.setUseCaches(false);
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("Content-Type",
                                "multipart/form-data;boundary=" + boundary);
                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data;name=\"type\"" + lineEnd);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes("item");
                        dos.writeBytes(lineEnd);

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"images\";filename=\""
                                + exsistingFileName + "\"" + lineEnd);
                        dos.writeBytes(lineEnd);
                        Log.e("MediaPlayer", "Headers are written");

                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // Read file
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        System.out.println(TAG + ": Image length " + bytesAvailable);
                        while (bytesRead > 0) {
                            try {
                                dos.write(buffer, 0, bufferSize);
                            } catch (OutOfMemoryError e) {
                                e.printStackTrace();
                                Log.e(TAG, "doInBackground: " + e.getMessage());
                            }
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                            Log.v("bytesRead", "bytesRead" + bytesRead);
                        }
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Amani Joseph
  • 391
  • 3
  • 11
  • Well, `newFile` is obviously `null`. Since you don't show us how `newFile` is initialized, we really can't say what went wrong. – markspace Feb 02 '22 at 15:44
  • I update the Question with how the code works @markspace – Amani Joseph Feb 02 '22 at 15:55
  • 1
    I can't post my answer explaining how to read the stacktrace since the question's been closed, so I'll just say the first line in the ``Caused by: java.lang.NullPointerException`` section is what threw it, and that's `at java.io.FileInputStream.` which is the ``FileInputStream`` constructor. You only have one parameter for that, ``newFile``, so that's what's null (and shouldn't be). If you look at your code, you initialise ``newFile = null``, and then you set it in your ``if/else`` block. **But only** if your ``try`` block succeeds, and if ``saveBitmapToFile`` doesn't return null – cactustictacs Feb 02 '22 at 16:05
  • 1
    Right. If this code throws an exception in the first part (`FileNotFound` for example) then `newFile` won't be initialized. This is why we should always *actually throw exceptions* and not just catch them and print them. You're disguising the true problem ("file not found" or some such) because you continue execution and then get a second error after the exception. – markspace Feb 02 '22 at 17:50

0 Answers0