Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

Janessa Bautista :

Why am I getting this error when selecting image in gallery?

Capturing of image using camera is working fine, but when I am selecting image in gallery, the error comes up.

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == CAMERA_REQUEST_CODE){

            if(resultCode == Activity.RESULT_OK){
                File f = new File(currentPhotoPath);
                IDProf.setImageURI(Uri.fromFile(f));
                Log.d("taffffffg", "ABsolute Url of Image is " + Uri.fromFile(f));

                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
                    bitmap=getResizedBitmap(bitmap, 100);
                    IDProf.setImageBitmap(bitmap);
                    BitMapToString(bitmap);
                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } else if(requestCode == GALLERY_REQUEST_CODE){
            if(resultCode == Activity.RESULT_OK){
                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                thumbnail=getResizedBitmap(thumbnail, 400);
                Log.w("path", picturePath+"");
                IDProf.setImageBitmap(thumbnail);
                BitMapToString(thumbnail);
            }

        }
    }

    public String BitMapToString(Bitmap userImage1) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        userImage1.compress(Bitmap.CompressFormat.PNG, 60, baos);
        byte[] b = baos.toByteArray();
        long lengthbmp = b.length;
        Document_img1 = Base64.encodeToString(b, Base64.DEFAULT);

        Log.d("byte_image", String.valueOf(lengthbmp));

        return Document_img1;
    }

    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = 120;
        int height = 180;

        float bitmapRatio = (float)width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

did anyone experience this? I already look for the similar problem here, and I still cant fix it. I just need to display the image and encode it base64, but it is having an error on resizing i think.

  • Here is the error that I am getting.

Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/temp.jpg: open failed: EACCES (Permission denied) AndroidRuntime: FATAL EXCEPTION: main Process: com.example.eplife, PID: 1494 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=105, result=-1, data=Intent { dat=content://media/external/images/media/592 flg=0x1 (has extras) }} to activity {com.example.eplife/com.example.eplife.ProfileModule.ChangePhoto}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at android.app.ActivityThread.deliverResults(ActivityThread.java:4998) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5041) at android.app.ActivityThread.access$1600(ActivityThread.java:229) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:7325) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1321) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1211) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:748) at com.example.eplife.ProfileModule.ChangePhoto.getResizedBitmap(ChangePhoto.java:239) at com.example.eplife.ProfileModule.ChangePhoto.onActivityResult(ChangePhoto.java:206) at android.app.Activity.dispatchActivityResult(Activity.java:7165) at android.app.ActivityThread.deliverResults(ActivityThread.java:4994) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5041)  at android.app.ActivityThread.access$1600(ActivityThread.java:229)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1875)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:7325)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1321)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1211) 

i had place this on my oncreate activity

   if (ContextCompat.checkSelfPermission(ChangePhoto.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ChangePhoto.this, new String[]{Manifest.permission.CAMERA}, 1);
        }
Janessa Bautista :

I already figured out what is the error.

it is the permission.

so first i need to declare this.

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

and this to to the oncreate

        // Check if we have read or write permission
        if (ContextCompat.checkSelfPermission(ChangePhoto.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ChangePhoto.this, new String[]{Manifest.permission.CAMERA}, 101);
        }

        int writePermission = ActivityCompat.checkSelfPermission(ChangePhoto.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int readPermission = ActivityCompat.checkSelfPermission(ChangePhoto.this, Manifest.permission.READ_EXTERNAL_STORAGE);

        if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    ChangePhoto.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        //End

and the problem with the Bitmap is solved. i think this depends on the android version because as i read this problem is only on the marshmallow version.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11485&siteId=1