Reputation: 151
When I try to open a file just after inserting it using ContentResolver on Android API Level 18 it throws the exception FileNotFoundException.
If I try to run the same code on API Level 17 it works fine.
String fileName = DateFormat.format("yyyyMMdd_hhmmss", new Date()).toString();
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, fileName);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
ContentResolver contentResolver = getContentResolver();
Uri uri = contentResolver.insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = contentResolver.openOutputStream(uri);
image.compress(Bitmap.CompressFormat.JPEG, 90, outstream);
outstream.close();
return uri;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I tried using Images.Media.insertImage() but it didn't work too. Looking source code of this method I realized that code looks much like mine.
Upvotes: 2
Views: 745
Reputation: 151
Unfortunately using ContentResolver is not working as expected. So I decided to use other approach.
try {
String fileName = DateFormat.format("yyyyMMdd_hhmmss", new Date()).toString();
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
dir.mkdirs();
File file = new File(dir, fileName + ".jpg");
OutputStream out = new FileOutputStream(file);
image.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
MediaScannerConnection.scanFile(this,
new String[] { file.toString() },
null,
null);
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 1