0

Problem

I am creating an Android app within Android Studio using Java. It needs a function that takes a bitmap image and saves it to a folder structure in internal memory. The images I'm working with are PNGs. My current implementation is based on the answer found here (Saving and Reading Bitmaps/Images from Internal memory in Android). I am very lost as to why not all of the log statements are being executed and no files are being created:

    private String saveToInternalStorage( Bitmap bitmapImage, String dataType, int zoom, int x, int y )
    {
        Log.w(TAG, "Function Started.");
        String imageDir = String.format( "%s/%d/%d", dataType, zoom, x );
        String imageName = String.format( "%d.png", y );

        ContextWrapper contextWrapper = new ContextWrapper( getContext() );
        Log.w(TAG, "Passed Context Wrapper.");

        // path to /data/data/app_name/app_data/<dataType>/<zoom>/<x>
        // - - - NO LOGS SHOWN PAST THIS POINT - - -
        File directory = contextWrapper.getDir( imageDir, Context.MODE_PRIVATE );
        Log.w(TAG, "Passed Directory Creation.");

        // Create image at imageDir (<y>.png)
        File imageFile = new File( directory, imageName );
        Log.w(TAG, "Passed File Creation.");

        FileOutputStream outputStream = null;
        Log.e(TAG, "Begining to Output to File.");
        try
        {
            outputStream = new FileOutputStream( imageFile );
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress( Bitmap.CompressFormat.PNG, 100, outputStream );
        }
        catch( Exception e )
        {
            Log.e(TAG, "Error Adding Image to Internal Storage.");
            e.printStackTrace();
        }
        finally
        {
            try
            {
                outputStream.flush();
                outputStream.close();
            }
            catch( Exception e )
            {
                Log.e(TAG, "Error Closing Output Stream.");
                e.printStackTrace();
            }
        }

        return directory.getAbsolutePath();
    }

The following two lines are the only relevant output shown in Logcat. I am not shown any errors and no other logs from the above function are shown.

2022-02-08 02:52:56.433 18914-18990/com.example.biomapper W/ContentValues: Function Started.
2022-02-08 02:52:56.434 18914-18990/com.example.biomapper W/ContentValues: Passed Context Wrapper.

What I've Tried

This is my third attempt at creating this function, and the closest I've gotten to making it work. I have looked at many other questions on Stack Overflow regarding this topic. I added many log statements to see where/what might be going wrong. I've tried using the file.exists() command to test if the file(s) were ever created. I am sure that the parameters given to this function when testing it are correct.

Any advice on saving images to internal storage, checking if the files exist, or improving my code in any way are greatly appreciated.

Matt N.
  • 53
  • 1
  • 10
  • `String imageDir = String.format( "%s/%d/%d", dataType, zoom, x );` That is not one directory but already three. Probably getDir() does not like that. For some tests change to `String imageDir = String.format( "%s-%d-%d", dataType, zoom, x );` as then it is one directory. But then still... getDir() expects part of a name. (The resulting directory name starts with 'app_'). Why dont you use getFilesDir()? – blackapps Feb 08 '22 at 11:00
  • @blackapps That would make sense. But based on the answer [here](https://stackoverflow.com/questions/11781260/what-is-the-difference-between-getdir-and-getfilesdir-on-android), it seems like getFilesDir() is nearly the same function? However, I will try creating one directory at a time and seeing if that works. – Matt N. Feb 08 '22 at 16:31

1 Answers1

0

In This Way I Saved the image in android folder Create a directory "xml" in res folder and paste

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.project/files/Pictures" />
</paths>

In Manifest file add this line under application

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.xyz.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path" />
</provider>

initialize this in your respective activity

File photoFile = null;

Edit this function according to your requirements !!

try {

                    photoFile = createImageFile();
                    displayMessage(getBaseContext(), photoFile.getAbsolutePath());

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        Uri photoURI = FileProvider.getUriForFile(this,"com.xyz.fileprovider",photoFile);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
                    }
                } catch (Exception ex) {
                    // Error occurred while creating the File
                    displayMessage(getBaseContext(), ex.getMessage().toString());
                }
Rahul Pandey
  • 520
  • 3
  • 15
  • I do not believe I'm using FileProvider and haven't defined the path in the XML. Would that go in the AndroidManifest.xml file? I found more information about FileProvider [here](https://developer.android.com/reference/kotlin/androidx/core/content/FileProvider), but a more concrete example would be super helpful. – Matt N. Feb 08 '22 at 16:41
  • You do not need FileProvider to create files. – blackapps Feb 08 '22 at 16:47
  • well i made an app where i would click the image and upload it to the server and i need to save that captured image in my internal memory So i used file provider.. I'll update my answer and see if it fits your requirement !! – Rahul Pandey Feb 09 '22 at 04:03