Search code examples
androidandroid-galleryandroid-camera-intent

How to take a picture and save it in a custom folder for my app visible in the Gallery


I´ve been struggling with this for a few days now and other answers posted in similar questions here on stackoverflow haven´t helped me.

What I want to do is set a custom ArrayAdapter to my ListView and inside this adapter I want to set an onClickListener to a button that appears in every item. Then I want the user to pick whether he wants to take a picture with the camera or choose a picture from the gallery. Then I want the picture to save in the app´s own folder inside Gallery. However, although the custom folder is created and visible in Gallery, the picture itself is stored in the Camera folder and I can see a broken file in the custom folder.

I´ve read photobasics on the devsite http://developer.android.com/training/camera/photobasics.html, but it did not help much. I implemented the onActivityResult inside my Fragment but the Uri path is different fro the one created in the adapter.

Here is the code:

  • In ArrayAdapter:

    photoPicker.setOnClickListener(new View.OnClickListener()
    {
        @Override public void onClick(View v)
        {
    
            // Camera.
            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = mContext.getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam)
            {
                final String packageName = res.activityInfo.packageName;
                final Intent intent = new Intent(captureIntent);
                intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                intent.setPackage(packageName);
                cameraIntents.add(intent);
            }
    
            // Filesystem.
            final Intent galleryIntent = new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    
            // Chooser of filesystem options.
            final Intent chooserIntent = Intent.createChooser(galleryIntent, "Vyber zdroj");
    
            // Add the camera options.
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
    
            if (chooserIntent.resolveActivity(mContext.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)
                {
                    chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                           Uri.fromFile(photoFile));
                    Log.i(TAG,"uri from file:"+Uri.fromFile(photoFile).toString());
                    chooserIntent.putExtra("path",mCurrentPhotoPath);
                    fragment.startActivityForResult(chooserIntent, FlowListUtils.getIdFromDate(experience.getDate()));
                }
            }
        }
    });
    
    
     private File createImageFile() throws IOException
    {
    
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    String storagePath = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES).getPath()+"/MyApp";
    
    File storageDir = new File(storagePath);
    storageDir.mkdirs();
    
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
    
    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    Log.i(TAG,"mCurrent Photo Path in adapter:"+mCurrentPhotoPath);
    return image;
    }
    
  • This code is in my Fragment

     @Override public void onActivityResult(int requestCode, int resultCode, Intent data)
     {
    super.onActivityResult(requestCode, resultCode, data);
    
    ExperienceAdapter.dateForPicture = requestCode;
    ExperienceAdapter.uriForPicture = data.getData();
    
    
    galleryAddPic(path);
    }
    
    
    private void galleryAddPic(String path)
    {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(ExperienceAdapter.mCurrentPhotoPath);
    
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    getActivity().sendBroadcast(mediaScanIntent);
    }
    

The path I add to the intent is file:/storage/emulated/0/Pictures/MyApp/JPEG_20140626_133228_1332202116.jpg but suddenly changes to content://media/external/images/media/6273 in the Intent return by onActivityResult.

Where am I going wrong?


Solution

  • Here is the function to save the Image,

    public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
        String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
        String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
        try {
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }