1

I am currently following this guide https://developer.android.com/training/camera/photobasics#TaskPath.

I am trying to take a photo and add it to my gallery, but whenever I take a photo, nothing is added to the gallery or the SD card where it's suppose to be stored. Here is my code written in Java for using the camera to take a photo.

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",  /* suffix */
            storageDir     /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case REQUEST_IMAGE_CAPTURE:
                galleryAddPic();
        }
    }
}
private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(currentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

I believe something is going wrong with generating the URI here or the intent is not putting the extra correctly. Any suggestions to fix?

if (photoFile != null) {
    Uri photoURI = FileProvider.getUriForFile(this,
        "com.example.android.fileprovider",
        photoFile);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
Dendric
  • 21
  • 2
  • But is the image file created to begin with? (Dont use the gallery to check). And if it is there and it has file size zero then you did that with file.createTempFIle(). Having said that i have to add that you followed a terrible exaple as you should not create a temp file with size 0 already. The only thing you need is an uri. – blackapps Apr 24 '21 at 08:16
  • I looked at the external storage on the emulator, but there is no file saved there either. How would I check if the file is created and stored correctly besides checking the emulator storage? – Dendric Apr 24 '21 at 16:50
  • `try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File }` If there is no exception then the file Is created and you can find it with any file explorer/manager on the emulator. – blackapps Apr 24 '21 at 16:58
  • You should also put a grant write flag on the camera intent. Is the camera launched? – blackapps Apr 24 '21 at 17:00
  • I tried restarting the application too and I found no files within the folder it is suppose to be saving too. – Dendric Apr 24 '21 at 18:12
  • I tried using this block of code and it did not throw any errors or show the toast message. `try { photoFile = createImageFile(); } catch (IOException ex) { ex.printStackTrace(); Toast.makeText(this, "failed to create file", Toast.LENGTH_SHORT).show(); }` The camera is launched with no problem, but when I take a photo nothing is saved. I checked to make sure that there was write permissions by using this. ActivityCompat.requestPermissions((Activity) this, PERMISSIONS, REQUEST ); – Dendric Apr 24 '21 at 18:13
  • No not request but putting a flag on the used intent was the advise. Read my comment! – blackapps Apr 24 '21 at 18:22
  • If you used that block of code you should be able to find all those files with file size 0. But not on an Android 11 device. – blackapps Apr 24 '21 at 18:24
  • `File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)` Pictures in your apps specific getExternalFilesDir() will never be scanned by the media store and hence will never be shown by gallery apps. – blackapps Apr 24 '21 at 18:28
  • I added this to add a flag on the used intent `takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);` I wiped the emulator and reinstalled the app and found that when I take a photo, it creates the directory correctly in `data/com.example.app/files/Pictures`, but there is no files in the folder itself. Also from the code in galleryAddPic(), I thought that code snippet would scan for the photo in the external storage. Is this not the case? Also I am running on API 28 – Dendric Apr 24 '21 at 18:31
  • `data/com.example.app/files/Pictures` ? My god... getExternalFilesDir() would give `/storage/emulated/0/Android/data/com.example.app/files/Pictures` Please use a file explorer/manager that tels you full paths. – blackapps Apr 24 '21 at 19:21
  • `I thought that code snippet would scan for the photo in the external storage. Is this not the case?` Sigh.... Reread my comment about the media store. – blackapps Apr 24 '21 at 19:24
  • I have found the images that show up in the androidstudio device file explorer as seen here. https://i.imgur.com/mRe6H6v.png. However, they do not show up on the phone itself when I browse through the same sdcard/ directory. Is there a way for me to make them show up or would I have to save the images through a different method entirely. – Dendric Apr 24 '21 at 19:53
  • On an api 28 device every file explorer should show them. Now what sizes do they have in Device File Explorer ? You know you can copy from there? If you want them to show up in 'the gallery' then you know now which directory NOT to use. – blackapps Apr 24 '21 at 20:00
  • The sizes are around 150-200 KB as seen in this image i.imgur.com/9vLDTaA.png. After shutting down and restarting the emulator, I found a new AOSP on IA emulator that I can access which holds all of the images I took. I am not sure why this appeared as it was not here before. How would I go about copying these files in my application? Would I have to change the way it is stored since the media scanner cannot access the files because they are private to my app. From what I am reading on the documentation, I should be using something related to MediaStore.Images. – Dendric Apr 24 '21 at 20:42
  • I tried implementing getExternalStoragePublicDirectory() for storing the photo, but I am getting permission denied errors even with write permissions not being able to be granted. I have code that request the permission but it is not showing up. I even tried going into the settings and manually giving it storage permissions and still does not work. – Dendric Apr 24 '21 at 21:01
  • I finally got the application to work, thanks for spending your time to help me out! – Dendric Apr 24 '21 at 21:20

1 Answers1

1

As specified by user blackapps

File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) Pictures in your apps specific getExternalFilesDir() will never be scanned by the media store and hence will never be shown by gallery apps. – blackapps 2 hours ago

I tried then using the public storage here:

File storageDir = Environment.getExternalStoragePublicDirectory()

I encountered a problem with write permissions never being requested. I found the solution here where I just needed to add this to my manifest

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

Dendric
  • 21
  • 2
  • Note: Gallery is still not adding pictures, but I think I can get rid since the pictures are accessible from the application in a separate folder. – Dendric Apr 24 '21 at 21:28