0

I want to store my images in a seperate folder after I take them. Taking images is done but I can store them only root folder of sdcard. Environment.getExternalStorageDirectory().getAbsolutePath() gives me /storage/emulated/0 path. What I want is creating another folder named what comes from edit.getText().toString() Thanks in advance.

private void startCapture() {

    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    if (cameraIntent.resolveActivity(getPackageManager()) != null) {

        File photoFile = null;
        try {
            photoFile = CreateImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(photoFile != null)
        {
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(cameraIntent, CAMERA_CAPTURE);
        }
    }
}

private File CreateImageFile() throws IOException
{
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = timeStamp + ".jpg";


    File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+edit.getText().toString());
    if (!f.exists()) {
        f.mkdirs();
    } else {
        f = new File(Environment.getExternalStorageDirectory(), edit.getText().toString() + "(2)");
        f.mkdirs();
    }

    File storageDirectory = new File(new File("/sdcard/"+edit.getText().toString),imageFileName);

    return storageDirectory;
}

@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {

    switch(requestCode)
    {
        case CAMERA_CAPTURE:
            if(resultCode == RESULT_OK)
            {
                Toast t = Toast.makeText(klasorAdiActivity.this,"Photo taken",Toast.LENGTH_SHORT);
                t.show();
                startCapture();
            }
            break;
    }
}

EDIT

For those of you who will look at here in the future. Never skip requesting user permisson programmaticly.

Here's how you get storage permission:

First define constants

private static String TAG = "StoragePermission";
private static final int REQUEST_WRITE_STORAGE = 112;

Second Permission method where you will check if permission is already granted or not and if not ask for user's permission

private void Permission() {
if (ContextCompat.checkSelfPermission(this,
        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    Log.i(TAG, "Permission to record denied");

    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {


    } else {
        ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
            REQUEST_WRITE_STORAGE);
    }
}
}

Third Permission Result

@Override
public void onRequestPermissionsResult(int requestCode,
                                   String permissions[], int[] grantResults)                   {
switch (requestCode) {
    case REQUEST_WRITE_STORAGE: {

        if (grantResults.length == 0
                || grantResults[0] !=
                PackageManager.PERMISSION_GRANTED) {

            Log.i(TAG, "Permission denied");

        } else {

            Log.i(TAG, "Permission granted");

        }
        return;
    }
}
}
Erayzer
  • 39
  • 1
  • 8
  • 1
    **Never hardcode paths**. Any time you see code that refers to something like `/sdcard/`, the author of that code has no idea what he is doing. Beyond that, you seem to be creating directories off of `Environment.getExternalStorageDirectory()`, then are ignoring that and returning a `storageDirectory` value that refers to a hardcoded `/sdcard/`. Try `File storageDirectory = new File(f,imageFileName);` and see if you have better luck. – CommonsWare Oct 24 '16 at 15:57
  • @CommonsWare tried this a moment ago and didnt work. I have `W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)` – Erayzer Oct 24 '16 at 16:44

2 Answers2

1

I think they are similar to your question

Community
  • 1
  • 1
Donald Wu
  • 698
  • 7
  • 20
1

You can try this..

private Uri imageToUploadUri;

    private File CreateImageFile() throws IOException
    {
        File defaultFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+APP_NAME+"/"+edit.getText().toString());
        if (!defaultFile.exists())
             defaultFile.mkdirs();

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = timeStamp + ".jpg";
        File file = new File(defaultFile,imageFileName);

        //renaming file if exist
        int i = 2; 
        while (file.exists()){
            file = new File(defaultFile, timeStamp + "(" + i + ")" + ".jpg");
            i++;
        }

        return file;
    }



    private void captureCameraImage() {
            Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
            //stored the image and get the URI
            imageToUploadUri = Uri.fromFile(CreateImageFile());
            startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);

          if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
               Toast t = Toast.makeText(klasorAdiActivity.this,"Photo taken",Toast.LENGTH_SHORT);
               t.show();
               if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    // do what ever you want with this image    
               }
          } 
    }
ZeroOne
  • 8,996
  • 4
  • 27
  • 45
  • thank you but it doesn't work either. Everything looks correct and I dont get the error from app's itself. I get gallery error. I have no idea why it can happen – Erayzer Oct 24 '16 at 18:38