I have the following problem:
when I try to start my camera, I can take a picture, even save it on my SD card, but when I am going to find a way to display on my device, I get errors.
My global variables are 2 (I used 1, but 2 is better to make sure this is a weird error):
private File photofile; private Uri mMakePhotoUri;
and this is my camera start function:
@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 the same i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri); startActivityForResult(i, num); //num would be 1 on calling function }
and my activity:
@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(); } ...... ...... ....... }
Always get a NullPointerException
But ... if I take the picture again, IT WORKS !! .
I read everything I could here ... but I have no logic when I change a global variable and I can not accept it again ...
Thanks in advance. Greetings.
Decision
As Alex Cohn said, my problem was that I called onCreate
before onActivityResult
due to possible out-of-memory (because sometimes it doesn’t do this), so I wanted the application to be “healthy” and I tried a few try / catch
, and so I get the data, even if it calls onCreate
or onActivityResult
for the first call, and I wrote this data in the Binding, as described in the link to restore our state .
Thanks!.