Android startCamera me da una Intención nula y ... ¿destruye mi variable global?
Tengo el siguiente problema:
Cuando intento encender mi cámara, puedo tomar la foto, incluso guardarla en mi sdcard, pero cuando obtengo la ruta para mostrarla en mi dispositivo, obtengo errores.
Mis variables globales son 2 (usé 1 pero 2 son mejores para asegurarme de que sea un error extraño):
private File photofile;
private Uri mMakePhotoUri;
y esta es mi función de inicio de cámara:
@SuppressLint("SimpleDateFormat")
public void farefoto(int num){
// For naming the picture
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String n = sdf.format(new Date());
String fotoname = "Immagine-"+ n +".jpg";
//Going through files and folders
File photostorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File photostorage2 = new File(photostorage, "Immagini");
System.out.println(photostorage+"\n"+photostorage2);
photostorage2.mkdirs();
// My file (global)
photofile = new File(photostorage2, fotoname);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //intent to start camera
// My URI (global)
mMakePhotoUri = Uri.fromFile(photofile);
new Bundle(); // I took this code from internet, but if I remove this line, it's the same
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, num); //num would be 1 on calling function
}
y mis resultados de actividad:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1){
try{ // tring my global URI
photo = f.decodeAndResizeFile(new File(mMakePhotoUri.getPath()));
}
catch(NullPointerException ex){
System.out.println("fail");
ex.printStackTrace();
try{ // Trying my global FILE
photo = BitmapFactory.decodeFile(photofile.getAbsolutePath());
} catch (Exception e){
e.printStackTrace();
Toast.makeText(this, "C'è stato un errore. Riprova a scattare la foto.", Toast.LENGTH_LONG).show();
}
......
......
.......
}
Siempre obteniendo NullPointerException
Pero...Si vuelvo a tomar la foto, FUNCIONA !!.
He leído todo lo que pude aquí ... pero no tiene lógica cuando modifico una variable global y no puedo volver a tomarla ...
Gracias por adelantado. Aclamaciones.
SOLUCIÓNComoAlex Cohn dicho, mi problema era que estaba llamandoonCreate
antes deonActivityResult
probablemente debido a una falta de memoria (porque a veces no lo hace), así que quería tener mi aplicación "saludable" y probé algunostry / catch
Y así obtengo los datos, incluso si está llamandoonCreate
oonActivityResult
para la primera llamada, y escribí esos datos en un paquete como se explica en el enlace derestaurando nuestro estado.
¡Gracias!.