This is my line code that I use to save pictures from camera and gallery on device:
Camera Intent:
private void abrirCamera() {
ContentValues values = new ContentValues();
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//Camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, CAMERA);
}
Gallery Intent:
public void abrirGaleria() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
This is onActivityResult that is used to save folders on device:
@NonNull
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onResume();
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY) {//Verify the requestCode
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);
int altura = bitmap.getHeight();//altura;
int largura = bitmap.getWidth();//largura
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
} else {
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
}
atualizarLista();
}
if (requestCode == CAMERA && data == null) {//Android 10 (Android Q > API 23)
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = Objects.requireNonNull(getActivity()).getContentResolver().query(image_uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String caminho = cursor.getString(column_index);//diretorio
cursor.close();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image_uri);
int altura = bitmap.getHeight();
int largura = bitmap.getWidth();
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
apagaFotoOriginal(caminho);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
atualizarLista();
}
if (requestCode == CAMERA && String.valueOf(data).equals("Intent { act=inline-data (has extras) }")) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(image_uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String caminho = cursor.getString(column_index);//diretorio
cursor.close();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image_uri);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "Title", null);
int altura = bitmap.getHeight();//altura;
int largura = bitmap.getWidth();//largura
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
apagaFotoOriginal(caminho);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
atualizarLista();
}
if (requestCode == CAMERA && data == null) {//Android 10 (Android Q > API 23)
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = Objects.requireNonNull(getActivity()).getContentResolver().query(image_uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String caminho = cursor.getString(column_index);//diretorio
cursor.close();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), image_uri);
int altura = bitmap.getHeight();
int largura = bitmap.getWidth();
if (largura > 450) {
if (altura > largura) {//retrato
bitmap = getResizedBitmap(bitmap, 450, 600);
saveImage(bitmap);
}
if (largura > altura) {//paisagem
bitmap = getResizedBitmap(bitmap, 600, 450);
saveImage(bitmap);
}
if (largura == altura) {//quadrado
bitmap = getResizedBitmap(bitmap, 450, 450);
saveImage(bitmap);
}
apagaFotoOriginal(caminho);
}
salvarBD();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Falhou!", Toast.LENGTH_SHORT).show();
}
atualizarLista();
}
}
}
Metod used to save pics on device, of accord with your Android Version:
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File diretorioAndroid8_9 = new File(Environment.getExternalStorageDirectory() + File.separator + IMAGE_DIRECTORY);
if (!diretorioAndroid8_9.exists()) {//cria o diretorio caso não existir
diretorioAndroid8_9.mkdirs();
}
try {
id = foto_ugbDao.proximoID(compet, codugb);
String teste = "";
if (id <= 9) {// ID <= 9
int a = id;
String b = String.format("%02d", a);
String fileName = compet + codugb + b;
if (verificaNomeArquivo(fileName)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {
salvarArquivoAPI23(bytes, diretorioAndroid8_9, b);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {
salvarArquivoAPI23(bytes, diretorioAndroid8_9, b);
}
}
} else {// id >= 10
String fileName = compet + codugb + id;
if (verificaNomeArquivo(fileName)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {//criação de arquivo com id maior que 10, em API de nivel inferior a 29 (Android Q)
salvarArquivoAPI23(bytes, diretorioAndroid8_9, fileName);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android 10 (Q)
salvarArquivoAPI29(myBitmap, bytes, fileName);
} else {
salvarArquivoAPI23(bytes, diretorioAndroid8_9, fileName);
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void salvarArquivoAPI23(ByteArrayOutputStream bytes, File diretorioAndroid8_9, String b) throws IOException {
String ss = compet + codugb + id;
File f = new File(diretorioAndroid8_9, ss);
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(context,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
}
private void salvarArquivoAPI29(Bitmap myBitmap, ByteArrayOutputStream bytes, String fileName) throws IOException {
OutputStream outputStream = null;
ContentResolver resolver = getActivity().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
String diretorioAndroid10 = Environment.DIRECTORY_PICTURES + IMAGE_DIRECTORY;
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, diretorioAndroid10);
Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
if (uri != null) {
outputStream = resolver.openOutputStream(uri);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
Log.println(Log.ERROR, "API29", String.valueOf(uri));
} else {
File f = new File(diretorioAndroid10, fileName + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(context,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
}
}
And the log return:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65538, result=-1, data=null} to activity {br.agr.terraviva.modelogestao/br.agr.terraviva.modelogestao.ui.act005.AuditoriaUGBActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 at android.app.ActivityThread.deliverResults(ActivityThread.java:5080) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5121) at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2183) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:241) at android.app.ActivityThread.main(ActivityThread.java:7604) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941) Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 at android.database.AbstractCursor.checkPosition(AbstractCursor.java:515) at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:138) at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:52) at android.database.CursorWrapper.getString(CursorWrapper.java:141) at br.agr.terraviva.modelogestao.ui.act005.FA04.onActivityResult(FA04.java:350) at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:170) at android.app.Activity.dispatchActivityResult(Activity.java:8136) at android.app.ActivityThread.deliverResults(ActivityThread.java:5073) at android.app.ActivityThread.handleSendResult(ActivityThread.java:5121) at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2183) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:241) at android.app.ActivityThread.main(ActivityThread.java:7604) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)