Search code examples
javaandroidandroid-cameraandroid-sdcardandroid-image

Images are not being saved in my camera app


I'm trying to make an app that detects motion and takes picture when the motion is detected. Its saving the picture when I don't try to save it in the directory(folder). But when I try it with the directory, the picture is not being saved even though the directory is being created successfully. What changes should I make to the following code in order to make it work:

 private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {

        File folder = new File(Environment.getExternalStorageDirectory() +
            File.separator + "XYX APP");
             boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
        if (success) {
        // Do something on success

    } else {
        // Do something else on failure
    }

        File photo = new File(new File(Environment.getExternalStorageDirectory()+"XYZ APP/"), name+ ".jpg");
        if (photo.exists()) {
            photo.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(photo.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Note: The file name is generated in the following instruction:

 String name = "MotDet_"+String.valueOf(System.currentTimeMillis());
            if (bitmap != null) createDirectoryAndSaveFile(name, bitmap);

Update It works with the following code but not with the code above :

    private void save(String name, Bitmap bitmap) {
        File photo = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
        if (photo.exists()) photo.delete();

        try {
            FileOutputStream fos = new FileOutputStream(photo.getPath());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.close();
        } catch (java.io.IOException e) {
            Log.e("PictureDemo", "Exception in photoCallback", e);
        }
    }

Solution

  • First of all you missed the FileSeperator before xyz

     File photo = new File(folder.getAbsolutePath()+"/XYZ APP/"+ name+ ".jpg");
    

    And your Function becomes

    private void createDirectoryAndSaveFile(String name, Bitmap bitmap) {
    
    File folder = new File(Environment.getExternalStorageDirectory() +
            File.separator + "XYZ APP");//here you have created different name
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
    if (success) {
        // Do something on success
    
    } else {
        // Do something else on failure
    }
    
    File photo = new File(folder.getAbsolutePath(), name+ ".jpg"); 
    if (photo.exists()) {
        photo.delete();
    }
    try {
        FileOutputStream out = new FileOutputStream(photo.getPath());
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    

    }

    Marshmello comes with RuntimePermissions in order for you to save file in external directory you need to ask permission first, like below code

    public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {
    
            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
    

    }

    permission result callback

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
          super.onRequestPermissionsResult(requestCode, permissions, grantResults);
           if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
              Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
              //resume tasks needing this permission
          }
       }
    

    before saving call isStoragePermissionsGranted() if it returns true proceed saving file.