Question

i Develop custom camera app in android but when i store image in external storage .and android 2.3 to 4.2.0 is complete work but android kitkat version not working .what's problem . my custom camera activity code below.

Please Help me!!

 public class CameraActivity extends Activity {

    Camera mCamera;
    CameraPreview mCameraPreview;
    protected static final int MEDIA_TYPE_IMAGE = 0;
    static String FilePAth = "";
    Button takePicture, btnGlr, btnCancelCamera;
    static String base64string = "";
    String ImageType;
    Boolean isSDPresent;
    final int RESULT_LOAD_IMAGE = 1;
    File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_preview);
        isSDPresent = android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
        mCamera = getCameraInstance();

        mCameraPreview = new CameraPreview(CameraActivity.this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);

        takePicture = (Button) findViewById(R.id.btnTakePicture);
        takePicture.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mCamera.takePicture(null, null, mPicture);
            }
        });

        Intent intent = getIntent();

        if (intent.hasExtra("ImageType")) {
            ImageType = getIntent().getStringExtra("ImageType").toString();

            Log.v("log", " ImageType in Camera Activity -- >  " + ImageType);
        }

        btnGlr = (Button) findViewById(R.id.btnGallary);
        btnGlr.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);

            }
        });

        btnCancelCamera = (Button) findViewById(R.id.btnCancelCamera);
        btnCancelCamera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intent = new Intent(getApplication(),
                        MarketPlaceActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        releaseCamera();
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }
    }

    private Camera getCameraInstance() {

        try {
            Log.v("log_tag", "camera try:::" + mCamera);
            mCamera = Camera.open();

        } catch (Exception e) {
            // cannot get camera or does not exist
            Log.v("log_tag", "camera catch:::" + mCamera);
            releaseCamera();
        }
        return mCamera;
    }

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());

        FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_"
                + timeStamp + ".jpg";

        Log.v("log", " FilePAth " + FilePAth);

        File mediaFile;
        mediaFile = new File(FilePAth);

        return mediaFile;
    }

    /*private String SaveImage_Sta(Bitmap finalBitmap, String name) {

        if (isSDPresent) {
            Log.i("isSDPresent yes", " path is==> " + isSDPresent);
            String root = Environment.getExternalStorageDirectory().toString()
                    + "/profile";
            File myDir = new File(root);
            myDir.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = name + ".jpg";
            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();
            }
        } else {

            Log.i("isSDPresent no ", " path is==> false ");
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            file = new File(directory, "profile.jpg");

            if (file.exists())
                file.delete();
            try {
                FileOutputStream fos = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.flush();
                fos.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file.toString();
    }*/

    PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            }
            try {

                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();

                if (ImageType.equals("AddPicture")) {
                    Intent i = new Intent(getBaseContext(),
                            MarketPlaceActivity.class);
                    i.putExtra("data", data);
                    startActivity(i);
                } else {
                    Intent returnIntent = new Intent();
                    returnIntent.putExtra("data", data);
                    setResult(RESULT_OK, returnIntent);
                    CameraActivity.this.finish();
                }

                // mCamera.startPreview();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    public void onBackPressed() {
        Intent returnIntent = new Intent();
        returnIntent.putExtra("path", FilePAth);
        setResult(RESULT_OK, returnIntent);
        finish();
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
                && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            Log.v("log", " picturePath --> selected Gallary Image path --> "
                    + picturePath);
            cursor.close();

            InputStream iStream;
            byte[] inputData = null;

            try {
                iStream = getContentResolver().openInputStream(selectedImage);
                inputData = getBytes(iStream);

                Log.v("log", " selected Gallary Image ByteArray --> "
                        + inputData);

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (ImageType.equals("AddPicture")) {
                Intent i = new Intent(getBaseContext(),
                        MarketPlaceActivity.class);
                i.putExtra("data", inputData);
                i.putExtra("image_from", "Gallary");
                startActivity(i);
            } else {
                Intent returnIntent = new Intent();
                returnIntent.putExtra("data", inputData);
                returnIntent.putExtra("image_from", "Gallary");
                setResult(RESULT_OK, returnIntent);
                CameraActivity.this.finish();
            }

            // ImageView imageView = (ImageView) findViewById(R.id.imgView);
            // imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
    }

    public byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }

}
Was it helpful?

Solution

As I said in my comment, Android 4.4 (KitKat) has changed how permissions are handled on the SD card. It is now best practice to make your own directory on the SD card to handle all files your app needs to write. Right now you are trying to access the Pictures folder which is not owned or created by your app. Change your getOutputMediaFile() contents to this:

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/MyCameraApp/");
    if (!mediaStorageDir.exists()) {
        mediaStorageDir.mkdir();
    }
    return mediaStorageDir;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top