I am creating an app that lets user select an image from gallery and store it in my DB. I am successful in doing that.
Now I want that selected image to be deleted from phone storage also. how do I do it then?
I might even want to restore it later in users gallery.
This is what I do to get image from gallery.
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
switch (requestCode)
{
case 42:
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
InputStream inputStream = null;
try
{
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
int maxHeight = 1920;
int maxWidth = 1920;
float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
saveImageToInternalStorage(bitmap, getFileName(uri));
bm.recycle();
bitmap.recycle();
finishActivity(42);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}
This is the Uri path I'm getting
content://com.android.providers.media.documents/document/image%3A5857
my onActivityResult looks like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
switch (requestCode)
{
case 42:
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
InputStream inputStream = null;
try
{
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
int maxHeight = 1920;
int maxWidth = 1920;
float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
saveImageToInternalStorage(bitmap, getFileName(uri));
bm.recycle();
bitmap.recycle();
finishActivity(42);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}