-3

This is my CameraActivity.java file. when i open the camera and take the picture it says "unfortunately application has stopped working".it capture the image and when try to load the image on image view it has stopped working.please help me to fix the problem.

package com.example.perade2016;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.ImageView;

public class CameraActivity extends Activity {
    private static final String LOG_TAG = "error";
    ImageView imageView;
    static final int CAM_REQUEST = 1;
    Date curentTime;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);

        verifyStoragePermissions(this);

        imageView = (ImageView)findViewById(R.id.imageView1);
        Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getFile();
        camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(camera_intent,CAM_REQUEST);

    }

    private File getFile()
    {
        curentTime = new Date();
        String root = Environment.getExternalStorageDirectory().toString();
        File folder = new File(root + "/Blue_&_Gold_Perade");
        if (!folder.mkdirs()) {
            Log.e(LOG_TAG, "Directory not created");
        }

        File image_file = new File(folder,"selfie_cam"+curentTime+".jpg");                    
        return image_file;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent         data) {
        setAndSaveImageWithOverlay(getBitmapOfSnappedImage());
        }

    public Bitmap getBitmapOfSnappedImage(){


        String root = Environment.getExternalStorageDirectory().toString();
        String path = root + "/Blue_&_Gold_Perade"+         "/selfie_cam"+curentTime+".jpg";

            File image = new File(path);
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap =         BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
            return bitmap;
        }

    public void setAndSaveImageWithOverlay(Bitmap snappedImage){
        Bitmap b = Bitmap.createBitmap(snappedImage.getWidth(),         snappedImage.getHeight(), Bitmap.Config.ARGB_8888);

        //the overlay png file from drawable folder

        if (snappedImage.getWidth() > snappedImage.getHeight()) {
            Bitmap overlay = BitmapFactory.decodeResource(getResources(),         R.drawable.overlay3);
            overlay =         Bitmap.createScaledBitmap(overlay,snappedImage.getWidth(),snappedImage.getHeight        (),false);
          //create canvas with a clean bitmap
            Canvas canvas = new Canvas(b);
            //draw the snappedImage on the canvas
            canvas.drawBitmap(snappedImage, 0, 0, new Paint());
            //draw the overlay on the canvas
            canvas.drawBitmap(overlay, 0, 0, new Paint());

            imageView.setImageBitmap(b);

            SaveImage(b);}
            else { 
            Bitmap overlay = BitmapFactory.decodeResource(getResources(),         R.drawable.overlay2);
            overlay =         Bitmap.createScaledBitmap(overlay,snappedImage.getWidth(),snappedImage.getHeight        (),false);


            //create canvas with a clean bitmap
            Canvas canvas = new Canvas(b);
            //draw the snappedImage on the canvas
            canvas.drawBitmap(snappedImage, 0, 0, new Paint());
            //draw the overlay on the canvas
            canvas.drawBitmap(overlay, 0, 0, new Paint());

            imageView.setImageBitmap(b);

            SaveImage(b);}
        }


    private void SaveImage(Bitmap finalBitmap) {

        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/Blue_&_Gold_Perade");
        myDir.mkdirs();
        String fname = "selfie_cam"+curentTime+".jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

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

    /**
     * Checks if the app has permission to write to device storage
     *
     * If the app does not has permission then the user will be prompted to     grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,     Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

}

This is the error code in logcat.

01-31 22:05:17.939: E/AndroidRuntime(3514): FATAL EXCEPTION: main
01-31 22:05:17.939: E/AndroidRuntime(3514): java.lang.RuntimeException:         Failure delivering result ResultInfo{who=null, request=1, result=0, data=null}         to activity {com.example.perade2016/com.example.perade2016.CameraActivity}:         java.lang.NullPointerException
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.deliverResults(ActivityThread.java:3000)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.handleSendResult(ActivityThread.java:3043)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.access$1100(ActivityThread.java:127)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread$H.handleMessage(ActivityThread.java:1188)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.os.Handler.dispatchMessage(Handler.java:99)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.os.Looper.loop(Looper.java:137)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.main(ActivityThread.java:4441)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         java.lang.reflect.Method.invokeNative(Native Method)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         java.lang.reflect.Method.invoke(Method.java:511)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         dalvik.system.NativeStart.main(Native Method)
01-31 22:05:17.939: E/AndroidRuntime(3514): Caused by:             java.lang.NullPointerException
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.example.perade2016.CameraActivity.setAndSaveImageWithOverlay(CameraActivity.        java:83)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         com.example.perade2016.CameraActivity.onActivityResult(CameraActivity.java:67)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.Activity.dispatchActivityResult(Activity.java:4649)
01-31 22:05:17.939: E/AndroidRuntime(3514):     at         android.app.ActivityThread.deliverResults(ActivityThread.java:2996)
01-31 22:05:17.939: E/AndroidRuntime(3514):     ... 11 more
Shan Nirmala
  • 37
  • 1
  • 7
  • What is line 83 in `CameraActivity`? – CommonsWare Feb 02 '16 at 12:59
  • 3
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Rohit5k2 Feb 02 '16 at 13:00
  • have a look here: http://stackoverflow.com/a/10357574/4252352 you're not doing any checking in OnActivityResult for request code / result code. – Mark Feb 02 '16 at 13:15
  • @CommonsWare, this is the line 82 and 83, "public void setAndSaveImageWithOverlay(Bitmap snappedImage){ Bitmap b = Bitmap.createBitmap(snappedImage.getWidth(), snappedImage.getHeight(),Bitmap.Config.ARGB_8888);" – Shan Nirmala Feb 02 '16 at 14:30

1 Answers1

0

There are a few problems here.

First, you assume that your process will be around while the camera app is in the foreground. That is not assured. Your process may be terminated. In that case, curentTime will be null in your new activity instance. You need to save your path to your desired image in the saved instance state Bundle and restore it from that same Bundle in the new activity instance.

Second, you are generating that path in two separate places, introducing the possibility of typos or other bugs. Create the path once and use that same value in both places.

Third, you are not handling the case where there is no picture at that path. That could be because the user elected not to take a picture. It also could be that the camera app that the user chose has a bug in its ACTION_IMAGE_CAPTURE support, where it is ignoring your EXTRA_OUTPUT value. You need to gracefully handle both cases.

Fourth, I do not recommend using & in a file path, as that is a reserved character.

Fifth, you are trying to take the picture without waiting for the user to grant you the runtime permission. Move your take-the-picture logic into onRequestPermissionsResult(), and only take the picture if you hold the permission there.

There are probably other issues with this code, but any of these could explain your symptoms.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491