Trying to save an image in a folder with specific folders that was not created

I managed to get photo1.jpg to save in Pictures/mockFolder , which I created on the SD card, here is the code for reference in the future.

 public class CameraActivity extends Activity { final int PICTURE_ACTIVITY = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/mockFolder/"; File newdir = new File(dir); newdir.mkdirs(); String file = dir + "photo1.jpg"; File newfile = new File(file); try { newfile.createNewFile(); } catch (IOException e) {} Uri outputFileUri = Uri.fromFile(newfile); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(cameraIntent, PICTURE_ACTIVITY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); AlertDialog msgDialog; if (resultCode == RESULT_CANCELED) { msgDialog = createAlertDialog("Alert", "Picture was not saved. Please try again.", "OK"); } else { msgDialog = createAlertDialog("Alert", "Picture was saved successfully.", "OK"); } msgDialog.show(); } private AlertDialog createAlertDialog(String title, String msg, String buttonText){ AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog msgDialog = dialogBuilder.create(); msgDialog.setTitle(title); msgDialog.setMessage(msg); msgDialog.setButton(buttonText, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int idx){ finish(); } }); return msgDialog; } public void finish() { super.finish(); } } 
+4
source share
2 answers

You probably need to create your own new file too.
After you have done File file = new File(path); , call createNewFile() ;
More truly:

 String dir = Environment.DIRECTORY_PICTURES + "mockFolder/"; String name = "photo1.jpg"; File file = new File(dir, name); file.createNewFile(); 
+4
source

You can improve your code by calling newFolder.mkdirs() instead of newFolder.mkdir() . mkdirs() creates all the folders necessary for the specified path.

Also, you forgot to add a slash after Environment.DIRECTORY_PICTURES when setting the path variable.

Also, make sure your application has write permission on the SD card.

Add this to AndroidManifest.xml:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

Environment.DIRECTORY_PICTURES contains only the folder name for the images. You need to specify the full path to the location.

 File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
+4
source

Source: https://habr.com/ru/post/1387062/


All Articles