0

I am working in android studio. Building an app in which i am using a camera. When i run my app the app works fine. I capture the image it does captured the image. But the folder i created is not showing in my gallery. I am saving images in my local storage and not in SD CARD. I was very curious that why the folder is not created as it doesn't gives me any error so it should be in my gallery. So i restarted my device and after restarting i can see the folder in my gallery and the images taken in it. I again open the app and took images from it but again the images were not shown in the folder.

Below is my code in which i am making ta directory for saving images

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        if(resultCode == Activity.RESULT_OK)
        {
            Bitmap bmp = (Bitmap)data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

            if(isStoragePermissionGranted())
            {
                SaveImage(bitmap);
            }


        }

}
 private void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
    Log.v(LOG_TAG, root);
    File myDir = new File(root + "/captured_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 1000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir,fname);
    if (file.exists())file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
        out.flush();
        out.close();


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

}

Below is the picture of my debugging

enter image description here

**Note: **

As i am using native camera so the pictures are saved in the camera roll folder i.e. the default folder in my device. But the image saved there is not the compressed one, the compress image should be saved in my created folder.

I am stuck to it and don't know what to do.

Any help would be highly appreciated.

Moeez
  • 494
  • 9
  • 55
  • 147
  • after `saveImage` method call this `sendBroadcast(new Intent( Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));` – sajan Feb 27 '17 at 14:09
  • tried and getting this error `java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=Intent { act=inline-data (has extras) }} to activity` – Moeez Feb 27 '17 at 14:18
  • **Before Android 4.4** ``sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));`` **From Android 4.4** ``sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));`` – sajan Feb 27 '17 at 14:21

2 Answers2

4

You need to invoke scanFile(Context context, String[] paths, String[] mimeTypes, MediaScannerConnection.OnScanCompletedListener callback) method of MediaScannerConnection.

MediaScannerConnection provides a way for applications to pass a newly created or downloaded media file to the media scanner service. This will update your folder with the newly saved media.

    private void SaveImage(Bitmap finalBitmap) {

        //....
        if(!storageDir.exists()){
               storageDir.mkdirs();
         }
        //...
        file.createNewFile();
        try {
            MediaScannerConnection.scanFile(context, new String[]  {file.getPath()} , new String[]{"image/*"}, null);
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
CoderP
  • 1,361
  • 1
  • 13
  • 19
  • in ` new String[]{"image/*"});` in place of `image/*` i will be placing my folder name ? – Moeez Feb 28 '17 at 05:28
  • You need to place the array of MIME types. Which in your case, if its only image media, will be image/* itself. – CoderP Feb 28 '17 at 05:36
  • Ok so no need to change it ? – Moeez Feb 28 '17 at 05:44
  • Still not able to view any folder in my gallery and now i am getting this `java.io.FileNotFoundException: /storage/emulated/0/captured_images/Image-951.jpg: open failed: ENOENT (No such file or directory)` and it's hitting at point `FileOutputStream out = new FileOutputStream(file);` – Moeez Feb 28 '17 at 06:39
  • I have made edits to the answer. create directory only if directory doesnot exist. Also after making sure that file does not already exist use file.createNewFile() method. Hope this helps – CoderP Feb 28 '17 at 07:03
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/136818/discussion-between-faisal1208-and-coderp). – Moeez Feb 28 '17 at 07:29
0

try this

private void saveBitmap(Bitmap bitmap) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = timeStamp + ".jpg";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        final String fileLoc = storageDir.getAbsolutePath() + "/folderName/" + imageFileName;
        File file = new File(fileLoc);
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        try {`enter code here`
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Richard K Maleho
  • 436
  • 6
  • 16