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

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);
        }

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.

Solved: attempt to invoke virtual method java lang string , attempt to invoke virtual method java lang string on a null object reference error pop up message please help me fix my issues it pop up when ever it feel like it . Yes, a factory reset will very likely fix the issue. Remember to back up any important information like contacts and pictures before. java – Attempt to invoke virtual method 'android.content.Context.getResources()' on a null object reference Posted by: admin May 10, 2020 Leave a comment Questions:

It clearly says that you don't have the file /storage/emulated/0/temp.jpg. It is called a FileNotFoundException in java.

Caused by java.lang.NullPointerException Attempt to invoke virtual , java.lang.NullPointerException. Attempt to invoke virtual method 'void com. newrelic.agent.android.tracing.TraceMachine.completeActivityTrace()' on a null� February 20, 2020 Java Leave a comment. Questions: I am setting a textview as HTML retrieved from Firebase database. When I am setting the question the I am adding another value called qid to the textview.

Check permission on manifest file, and allow all permissions.

For Write

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

For Read:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Attempt to invoke virtual method on a null object reference � Issue , Attempt to invoke virtual method on a null object reference #347. Closed. Manu404 opened this issue on Sep 21, 2017 � 6 comments. Closed� Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference Ask Question Asked 5 years, 2 months ago

Check if thumbnail got from the bitmap factory is null:

[...]
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
bitmap=getResizedBitmap(bitmap, 100);
[...]

Probably the file from picturePath does not exist or has some problem, so thumbnail gets null, and when calling to getResizedBitmap, and then inside Bitmap.createScaledBitmap.

EDIT:

With the full stack, the error is clearly that /storage/emulated/0/temp.jpg does not exist or app has not access rights.

Check if the file exists, check also the file permissions (open it with other app), and if exists and other app can read it, then check the manifest (maybe the app does not have permissions to read the storage).

Attempt to invoke virtual method 'java.lang.String android , NullPointerException: Attempt to invoke virtual method 'java.lang.String android. content.Context.getPackageName()' on a null object reference #45. "Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference". My code is working in main activity when I remove the code for the listView element, in it's place I've tested to ensure the passed in array outputs correctly (which it does).

add this line in manifest file

<manifest ... >
    //This attribute is "false" by default on apps targeting Android Q. 
   <application 
          android:requestLegacyExternalStorage="true" ... >
...
   </application>
</manifest>

java lang NullPointerException Attempt to invoke virtual method , java lang NullPointerException Attempt to invoke virtual method. 3,694 views3.6K views Duration: 5:22 Posted: Aug 9, 2019 attempt to invoke virtual method java lang string on a null object reference error pop up message please help me fix my issues it pop up when ever it feel like it .

How to fix an attempt to invoke virtual methods on a null object , In your code, surround the method invocation with a check for null, and don't invoke if it's null. Don't know about Java syntax, but C# can do this null check just by� NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference Ask Question Asked 5 years, 9 months ago

Android Studio: attempt to invoke virtual method on a null object , Hi, i'm new to this forum but i've already have some experience with Processing. Recently i started learning Android programming using� Attempt to invoke virtual method 'void android.widget.edittext.settext(java.lang.charsequence)' on a null object reference Rate this: Please Sign up or sign in to vote.

Attempt to invoke virtual method 'void com.amazon.device.ads , Attempt to invoke virtual method 'void com.amazon.device.ads.MetricsCollector. on a null object reference. I see the following exception� [Android] NullPointerException - Attempt to invoke virtual method 'void com.swmansion.reanimated.nodes.ValueNode.setValue(java.lang.Object)' on a null object reference #559 Closed alimek opened this issue Jan 16, 2020 · 1 comment

Comments
  • Please post the full stacktrace. You are not calling getWidth in your code.
  • @f1sh i am using the function getResizedBitmap sir
  • Hi sir, the file path does exists. ``` Bitmap thumbnail = (BitmapFactory.decodeFile("/storage/emulated/0/DCIM/Screenshots/Screenshot_20191129-014400.png")); Log.d("picture_path",String.valueOf(picturePath)); Log.d("thumbttt",String.valueOf(thumbnail)); ``` But when it goes to the Bitmap it is becoming null.
  • i have that permission sir.
  • please check selected image is not null
  • Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/temp.jpg: open failed: EACCES (Permission denied) i think this is the one that is causing the problem, how can i put this on the ContentCompact sir?
  • First of all, check if the file exist, then if exist, probably is caused by permissions, do the app has access to the storage? check the manifest.
  • did you check if you can read that file with other app? did the file exist?
  • Use some file explorer like ES File Explorer or similar.
  • in this part String picturePath = c.getString(columnIndex); c.close(); Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath)); i can still log the picturePath, but when i got to the Bitmap thumbnail, that is where it is getting null BitmapFactory.decodeFile(picturePath)