Skip to content Skip to sidebar Skip to footer

Null Pointer Exception When Grabbing Picture From Gallery

i have the following code, which is used to grab images (either from camera or gallery) and then display it on an ImageView: @Override protected void onActivityResult(int requestCo

Solution 1:

You onActivityResult is very messy.

Try to write code something like this way.. Below tow method is define to capture image from camera and taking image from gallery respectively.

protectedvoidcaptureFromCamera() {
        // TODO Auto-generated method stub
        Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(cameraIntent,
                UploadProfilePicActivity.REQ_CAMERA);
    }

    privatevoidselectImageFromGallery() {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,
                getString(R.string.upload_profile_photo)),
                UploadProfilePicActivity.REQ_GALLERY);
    }

Now onActivityResult your code could be something like this..

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == UploadProfilePicActivity.REQ_GALLERY && data != null
                && data.getData() != null) {
            Uri_uri= data.getData();
            try {
                BitmapprofileBmp= Media.getBitmap(getContentResolver(), _uri);
                if (profileBmp != null) {
                    image.setImageBitmap(profileBmp);
                }

            } catch (OutOfMemoryError e) {
                Utility.displayToast(context,
                        getString(R.string.err_large_image));
            } catch (Exception e) {

            }
        } elseif (requestCode == UploadProfilePicActivity.REQ_CAMERA
                && data != null) {
            try {
                BitmapprofileBmp= (Bitmap) data.getExtras().get("data");
                if (profileBmp != null) {
                    image.setImageBitmap(profileBmp);
                }
            } catch (OutOfMemoryError e) {
                Utility.displayToast(context,
                        getString(R.string.err_large_image));
            } catch (Exception e) {
            }
        }
    }

A better imnplementation of onActivityResult using the parameters i.e requestCode and responseCode

Solution 2:

try this code:

create a imageview in your xml

ImageView photoFrame;
publicstaticfinalint REQ_CODE_PICK_IMAGE         = 101;

in oncreate add this:

  photoFrame.setOnClickListener(newOnClickListener() {

            @OverridepublicvoidonClick(View arg0) {
                try
                {
                    IntentgalleryIntent=newIntent(Intent.ACTION_PICK,
                               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(galleryIntent, REQ_CODE_PICK_IMAGE); 
                }catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        });

in OnActivityResult add this code:

protectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) { 
    case REQ_CODE_PICK_IMAGE:
        if(resultCode == RESULT_OK)
        {  
            UriselectedImage= data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursorcursor= getContentResolver().query(
                               selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();

            intcolumnIndex= cursor.getColumnIndex(filePathColumn[0]);
            photoPath = cursor.getString(columnIndex);
            cursor.close();
            photoFrame.setImageBitmap(Utils.getScaledImage(photoPath, 120, 120));
        }
    }
}

create a class for Utils, add this code in it:

publicstatic Bitmap getScaledImage(String path, int width, int height){
        try {
            //decode image size
            BitmapFactory.Optionso=newBitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path ,o);              
            //Find the correct scale value. It should be the power of 2.finalint REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale++;
            }

            //decode with inSampleSize
            BitmapFactory.Optionso2=newBitmapFactory.Options();
            o2.inSampleSize=scale;
            BitmapscaledPhoto= BitmapFactory.decodeFile(path, o2);
            scaledPhoto = Bitmap.createScaledBitmap(scaledPhoto, width, height, true);
            return scaledPhoto;
        } 
        catch (Exception e) {
            e.printStackTrace();
        }
        returnnull;
    }

with this code you can select a image from gallery and you can view image on Imageview

Solution 3:

Try my working code, The gallery images need to be queried from mediastore using its id

@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(resultCode == RESULT_OK)
    {
        if(requestCode == CAMERA_PIC_REQUEST)
        {               
            loadCameraImage();
            // Loading from camera is based on the intent passed
        }
        elseif(requestCode == SELECT_PICTURE)
        {
            UricurrentUri= data.getData();
            StringrealPath= getRealPathFromURI(currentUri);   
    // You will get the real path here then you can work with that path as normal
        }
    }

}

    // Gets the real path from MEDIApublic String getRealPathFromURI(Uri contentUri) {

    String [] proj={MediaStore.Images.Media.DATA};
    Cursorcursor= getContentResolver().query( contentUri, proj, null, null, null); 
    intcolumn_index= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();

    return cursor.getString(column_index);
}

Post a Comment for "Null Pointer Exception When Grabbing Picture From Gallery"