App failing when an image is selected

5

I'm trying to get an image using an Intent, but when I select the image, my application closes immediately. This is my current code:

private void capturarFoto() {

    String nameFoto = DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString();

    caminhoFoto = new File(Environment.getExternalStorageDirectory(),nameFoto);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(caminhoFoto));
    getActivity().startActivityForResult(intent, 1);
}

It should call the onActivityResult method after image selection, but unfortunately closes with no error in Logcat.

Is there something wrong?

LOGCAT

    
asked by anonymous 04.02.2014 / 20:51

2 answers

1

For you to capture an image through the camera, you must first create an intent for the code similar to yours:

private static final CAMERA=1; //o actionCode que voce usara no onActivityResult
private void intentParaTirarFoto(int codigoDePedido) {
    Intent intentParaTirarFoto= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intentParaTirarFoto, codigoDePedido);
}

After that in the ActivityResult method you do:

@Override
public void onActivityResult(int codigoDePedido, int resultado, Intent dados) {

    super.onActivityResult(codigoDePedido, resultado, dados);

    if(codigoDePedido==CAMERA && resultado==getActivity().RESULT_OK)
    {
        Bitmap bitmapImage=(Bitmap)data.getExtras().get("data");
                    //apartir daqui voce pode gravar a imagem ou fazer alguma outra coisa com o bitmap
                  gravarImagem(bitmapImage);

    }

}

below the implementation of the code to save the image in the mobile:

private void gravarImagem(Bitmap bitmap) {

    String root = Environment.getExternalStorageDirectory().toString();
    File file;
    File minhaPasta= new File(root + "/Pictures/Testando"); 
    Date date=new Date();
    long timeStamp=date.getTime();
    if(!myDir.exists())
    {
        myDir.mkdir(); //cria uma nova pasta caso a espicificada acima nao exista
    }
    String nomeFicheiro= "TestandoCamera"+timeStamp+".jpg";
     file= new File (myDir, fname);
    if (file.exists ()) file.delete (); 
    try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
    Log.e("GRAVOU", "IMAGEM GRAVADA NO CELULAR");
}
    
18.02.2014 / 14:07
0

As you are accessing the getActivity (). startActivityForResult (intent, 1); I believe you are accessing this code through a Fragment. Note that since you are calling this method via Activity, you should expect the onActivityResult of your Activity is called and not the onActivityResult of your Fragment. Can you check that? By the information given, that's what you can deduce.

    
14.02.2014 / 03:22