-1

Below is my Camera Handler:

public class CameraHandler {
    public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001,
            CROP_GALLARY_REQUEST = 1002;
    private Intent imageCaptureintent;
    private boolean isActivityAvailable;
    Context context;
    private List<ResolveInfo> cameraList;
    List<Intent> cameraIntents;
    Uri outputFileUri;
    Intent galleryIntent;
    Uri selectedImageUri;
    private String cameraImageFilePath, absoluteCameraImagePath;
    Bitmap bitmap;
    ImageView ivPicture;

    String ivPicture1 = String.valueOf(ivPicture);

    public CameraHandler(Context context) {
        this.context = context;
        setFileUriForCameraImage();
    }

    public void setIvPicture(ImageView ivPicture) {
        this.ivPicture = ivPicture;
    }

    private void setFileUriForCameraImage() {
        File root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "MyDir" + File.separator);
        root.mkdirs();
        final String fname = "image.jpg";
        final File sdImageMainDirectory = new File(root, fname);
        absoluteCameraImagePath = sdImageMainDirectory.getAbsolutePath();
        outputFileUri = Uri.fromFile(sdImageMainDirectory);
    }

    public String getCameraImagePath() {
        return cameraImageFilePath;
    }

    private void getActivities() {
        imageCaptureintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        PackageManager packageManager = ((Activity) context)
                .getPackageManager();
        this.cameraList = packageManager.queryIntentActivities(
                imageCaptureintent, 0);
        if (cameraList.size() > 0) {
            isActivityAvailable = true;
        } else {
            isActivityAvailable = false;
        }
    }

    private void fillCameraActivities() {
        getActivities();
        if (!isActivityAvailable) {
            return;
        }
        cameraIntents = new ArrayList<Intent>();
        for (ResolveInfo resolveInfo : cameraList) {
            Intent intent = new Intent(imageCaptureintent);
            intent.setPackage(resolveInfo.activityInfo.packageName);
            intent.setComponent(new ComponentName(
                    resolveInfo.activityInfo.packageName,
                    resolveInfo.activityInfo.name));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            cameraIntents.add(intent);
        }
    }

    private void fillGallaryIntent() {
        galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_PICK);
    }

    public void showView() {
        fillCameraActivities();
        fillGallaryIntent();
        // Chooser of filesystem options.
        final Intent chooserIntent = Intent.createChooser(galleryIntent,
                "Select Source");

        // Add the camera options.
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                cameraIntents.toArray(new Parcelable[] {}));

        ((Activity) context).startActivityForResult(chooserIntent,
                IMAGE_PIC_CODE);
    }

    private Bitmap getBitmapFromURL(String src) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(src, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 192, 256);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(src, options);

    }

    private int calculateInSampleSize(BitmapFactory.Options options,
                                      int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2
            // and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null,
                    null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public void onResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == IMAGE_PIC_CODE) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    Log.v("", "ics");
                } else {
                    Log.v("", " not ics");
                }
                boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();

                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action
                                .equals(MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH
                            && action != null) {
                        Log.v("", "action = null");
                        isCamera = true;
                    } else {
                        Log.v("", "action is not null");
                    }
                }
                if (isCamera) {
                    selectedImageUri = outputFileUri;
                    onResultCameraOK();
                } else {
                    selectedImageUri = data == null ? null : data.getData();
                    onResultGalleryOK();
                }
            }
        }

        if (requestCode == CROP_CAMERA_REQUEST) {
            if (resultCode == Activity.RESULT_OK) {
                resultOnCropOkOfCamera(data);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                resultOnCroppingCancel();
            }
        }

        if (requestCode == CROP_GALLARY_REQUEST) {
            if (resultCode == Activity.RESULT_OK) {
                resultOnCropOkOfGallary(data);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                resultOnCroppingCancel();
            }
        }

    }

    private void doCropping(int code) {
        Log.v("", this.cameraImageFilePath);
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(selectedImageUri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 256);
        cropIntent.putExtra("outputY", 256);
        cropIntent.putExtra("return-data", true);
        try {
            ((Activity) context).startActivityForResult(cropIntent, code);
        } catch (Exception e) {

        }
    }

    private void onResultCameraOK() {
        this.cameraImageFilePath = absoluteCameraImagePath;
        this.bitmap = getBitmapFromURL(cameraImageFilePath);
        doCropping(CROP_CAMERA_REQUEST);
    }

    private void onResultGalleryOK() {
        this.cameraImageFilePath = selectedImageUri.toString();
        this.bitmap = getBitmapFromURL(getRealPathFromURI(context,
                selectedImageUri));
        doCropping(CROP_GALLARY_REQUEST);
    }

    private void resultOnCropOkOfCamera(Intent data) {
        this.bitmap = data.getExtras().getParcelable("data");
        Log.v("", "cameraImageFilePath on crop camera ok => "
                + cameraImageFilePath);
        setImageProfile();
    }

    private void resultOnCropOkOfGallary(Intent data) {
        Bundle extras2 = data.getExtras();
        this.bitmap = extras2.getParcelable("data");
        setImageProfile();
    }

    private void resultOnCroppingCancel() {
        Log.v("", "do cropping cancel" + cameraImageFilePath);
        setImageProfile();
    }

    private void setImageProfile() {
        Log.v("", "cameraImagePath = > " + cameraImageFilePath);
        if (ivPicture != null) {
            if (bitmap != null) {
                ivPicture.setImageBitmap(bitmap);

                String ivPicture =ConDetTenthFragment.getStringImage(bitmap);

                Log.d("byte code -", ivPicture);

                /*Intent i = new Intent(context, ImageUpload.class);

                String getrec = ivPicture;

                //Create the bundle
                Bundle bundle = new Bundle();

                //Add your data to bundle
                bundle.putString("moin", getrec);

                //Add the bundle to the intent
                i.putExtras(bundle);

                //Fire that second activity
                context.startActivity(i);*/

            } else {
                Log.v("", "bitmap is null");
            }
        }
    }

    public String getVar1() {
        return ivPicture1;
    }

    /*public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }*/
}

Below is my Fragment Code:

public class ConDetTenthFragment extends Fragment {

    static String FileByte;
    String FileName;
    String resultlog;

    ImageView ivProfile;
    Context context = getActivity();
    Button btnUpload, send;
    CameraHandler cameraHandler;
    private ProgressDialog pDialog;

    static String abc;

       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View rootView = inflater.inflate(R.layout.con_det_tenth_fragment, container, false);
           /*TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
           tv.setText(getArguments().getString("msg"));*/

           ivProfile = (ImageView) rootView.findViewById(R.id.iv_upload);
           btnUpload = (Button) rootView.findViewById(R.id.btn_upload_image);
           send = (Button) rootView.findViewById(R.id.btnsend);
           cameraHandler = new CameraHandler(context);
           cameraHandler.setIvPicture(ivProfile);

           // Progress dialog
           pDialog = new ProgressDialog(getActivity());
           pDialog.setCancelable(false);
           pDialog.setMessage("Please Wait");


           btnUpload.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {

                   cameraHandler.showView();

               }
           });

           send.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   new async().execute();
               }
           });


       return rootView;
   }


    public static ConDetTenthFragment newInstance(String text) {

        ConDetTenthFragment f = new ConDetTenthFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }


    public static String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        abc = encodedImage;

        //encodedImage = FileByte.setText().toString();

        return encodedImage;
    }

    // Async task to perform login operation
    class async extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... params) {

            //Get the bundle
            /*Bundle bundle = getIntent().getExtras();

            //Extract the data…
            String stuff = bundle.getString("moin");*/

            SoapObject request = new SoapObject(namespace, method_name);
            request.addProperty(parameter, abc);//add the parameters
            request.addProperty(parameter2, "moin.jpeg");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//set soap version
            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;
            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
                // this is the actual part that will call the webservice
                androidHttpTransport.call(soap_action, envelope);
                //  SoapPrimitive prim = (SoapPrimitive) envelope.getResponse();  // Get the SoapResult from the envelope body.
                SoapObject response = (SoapObject) envelope.bodyIn;
                //  resultlog=prim.toString();

                hideDialog();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return resultlog;

        }
    }


    /*@Override
    public void onClick(View view) {
        if (view == btnUpload) {
            cameraHandler.showView();
        }
        if (view == send) {
            new async().execute();
        }
    }*/

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        cameraHandler.onResult(requestCode, resultCode, data);
        Log.v("", "code = > " + requestCode);
    }
    // this is used to show diologue
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    // this is used to hide diologue
    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}

Below is my Log Cat:

FATAL EXCEPTION: main
Process: code.meter.securemeter.com.securemeter, PID: 10492
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.app.Activity.getPackageManager()' on a null object reference
    at code.meter.securemeter.com.securemeter.helper.CameraHandler.getActivities(CameraHandler.java:72)
    at code.meter.securemeter.com.securemeter.helper.CameraHandler.fillCameraActivities(CameraHandler.java:83)
    at code.meter.securemeter.com.securemeter.helper.CameraHandler.showView(CameraHandler.java:106)
    at code.meter.securemeter.com.securemeter.fragment.ConDetTenthFragment$1.onClick(ConDetTenthFragment.java:76)
    at android.view.View.performClick(View.java:5242)
    at android.widget.TextView.performClick(TextView.java:10540)
    at android.view.View$PerformClick.run(View.java:21185)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:6856)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Full logcat please. – Vucko Jul 16 '16 at 15:15
  • Seems like this line `PackageManager packageManager = ((Activity) context) .getPackageManager();` produces the error. `context` seems to be null. – Vucko Jul 16 '16 at 15:27
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Draken Jul 20 '16 at 16:28

1 Answers1

0

Problem is happening because you are passing a null context to CameraHandler

Change your ConDetTenthFragment as follows:

public class ConDetTenthFragment extends Fragment {

    Context context;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getAcitivity();
        cameraHandler = new CameraHandler(context);
        ....
    }
}

Also, I think you don't need to Cast a context to Activity.

Just call (in CameraHandler):

PackageManager packageManager = context.getPackageManager();

Issue

Basically, the issue happened because you are creating your context as follows:

public class ConDetTenthFragment extends Fragment {
    Context context = getActivity();
    ...
}

When your Fragment is created, context = getActivity() is created also. However, at this time, your fragment is not attached yet and this way, getActivity() returns null.

guipivoto
  • 18,327
  • 9
  • 60
  • 75
  • Thanks Guilherme. context = getActivity(); giving cannot resolve method getActivity(); in my fragment. –  Jul 19 '16 at 08:18
  • Hi Guilherme. I solved above error but now it is not asking for crop and not showing selected image in imageview –  Jul 19 '16 at 08:22