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.