当我改变拍摄裁剪图像的相机方向时,为什么会丢失数据?

时间:2014-12-15 12:52:36

标签: java android crop

我正在做一个应用程序从相机拍摄图像然后裁剪它,但有些我如何丢失我的活动的对象,当它返回时,我得到NullPointerExeception,在它的OnCreate方法。但是当我从画廊中选择一个图像时,它可以正常工作,因为它不会关闭活动。

public void onClick(DialogInterface dialog, int item) {
    if (items[item].equals("Camera")) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, Constants.PICK_FROM_CAMERA);
    } else if (items[item].equals("Galeria")) {

        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        // ******** code for crop image
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("max-height", 800);
        intent.putExtra("max-width", 800);
        intent.putExtra("return-data", true);
        intent.putExtra("scaleType", "centerCrop");
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        try {
             startActivityForResult(Intent.createChooser(intent,
             "Complete action using"), Constants.PICK_FROM_GALLERY);
        } catch (ActivityNotFoundException e) {
        }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Bitmap tempImage;
    OutputStream fOut = null;

    File root = new File(Environment.getExternalStorageDirectory()
            + File.separator);

    try {
        File sdImageMainDirectory = new File(root, "foto.jpg");
        fOut = new FileOutputStream(sdImageMainDirectory);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (requestCode == Constants.PICK_FROM_CAMERA) {
        root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        saveBitmap(photo, Environment.getExternalStorageDirectory()
                + File.separator + "foto.jpg");
        try{
            cropCapturedImage(Uri.fromFile(root));
        }catch(ActivityNotFoundException aNFE){
            //display an error message if user device doesn't support
            String errorMessage = "Desculpe, seu dispositivo não suporta Crop!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    if (requestCode == Constants.PICK_FROM_GALLERY && data != null) {
        Bundle extras2 = data.getExtras();
        if (extras2 != null) {
            Bitmap photo = extras2.getParcelable("data");
            this.photo.setImageBitmap(photo);

            this.photo.buildDrawingCache();
            tempImage = this.photo.getDrawingCache();

            try {
                tempImage.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                fOut.flush();
                fOut.close();
                BasicUserPerson.getInstance().setPhotoPath(
                        Environment.getExternalStorageDirectory()
                        + File.separator + "foto.jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //user is returning from cropping the image
    else if(requestCode == Constants.PIC_CROP && data != null){
        //get the returned data
        Bundle extras = data.getExtras();
        if (extras != null){

            Bitmap thePic = (Bitmap) data.getExtras().get("data");
            saveBitmap(thePic, Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");

            photo.setImageBitmap(thePic);
            BasicUserPerson.getInstance().setPhotoPath(
                    Environment.getExternalStorageDirectory()
                    + File.separator + "foto.jpg");
        }
    }
}

public void saveBitmap(Bitmap photo, String path) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    File f = new File(path);
    try {
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void cropCapturedImage(Uri picUri){
    Intent cropIntent = new Intent("com.android.camera.action.CROP");
    cropIntent.setDataAndType(picUri, "image/*");
    cropIntent.putExtra("crop", "true");
    cropIntent.putExtra("aspectX", 1);
    cropIntent.putExtra("aspectY", 1);
    cropIntent.putExtra("outputX", 256);
    cropIntent.putExtra("outputY", 256);
    cropIntent.putExtra("return-data", true);
    cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    startActivityForResult(cropIntent, Constants.PIC_CROP);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dados_pessoais);

    fullName = (EditText) findViewById(R.id.edtFullName);
    cpf = (EditText) findViewById(R.id.edtCpf);
    email = (EditText) findViewById(R.id.edtDadEmail);
    ddd = (EditText) findViewById(R.id.edtDadDDD);
    telefone = (EditText) findViewById(R.id.edtDadTele);
    ddd2 = (EditText) findViewById(R.id.edtDadDDD2);
    celular = (EditText) findViewById(R.id.edtDadTel);
    btSalvar = (ImageView) findViewById(R.id.imgSalvar);
    head = (ImageView) findViewById(R.id.imgDadosHead);
    sexo = (Spinner) findViewById(R.id.spnSex);
    birthday = (EditText) findViewById(R.id.edtBrithday);
    civil = (Spinner) findViewById(R.id.spnCivil);
    loadingCity = (ImageView) findViewById(R.id.imgLoadingCity);
    escolaridade = (Spinner) findViewById(R.id.spnEscolaridade);
    cep = (EditText) findViewById(R.id.edtCep);
    state = (Spinner) findViewById(R.id.spnState);
    city = (Spinner) findViewById(R.id.spnCity);
    endereco = (EditText) findViewById(R.id.edtEndereco);
    bairro = (EditText) findViewById(R.id.edtBairro);
    num = (EditText) findViewById(R.id.edtNum);
    comp = (EditText) findViewById(R.id.edtComp);
    photo = (ImageView) findViewById(R.id.imgPhoto);

    btSalvar.setOnClickListener(this);
    photo.setOnClickListener(this);

    //Line of error
    if (!User.getInstance().getFullName().equals("null") && !User.getInstance().getFullName().equals("")){
        fullName.setText(User.getInstance().getFullName());
    }
    if (!BasicUserPerson.getInstance().getPersonRegistration().equals("null") && !BasicUserPerson.getInstance().getPersonRegistration().equals("")){
        cpf.setText(BasicUserPerson.getInstance().getPersonRegistration());
    }
    if (!User.getInstance().getEmail().equals("null") && !User.getInstance().getEmail().equals("null")){
        email.setText(User.getInstance().getEmail());
    }
    email.setKeyListener(null);
    if (!BasicUserPerson.getInstance().getMobilePhone().equals("null") && !BasicUserPerson.getInstance().getMobilePhone().equals("")){
        String tel = BasicUserPerson.getInstance().getMobilePhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd.setText(tel.subSequence(0, 2));
        celular.setText(tel.substring(2));
    }
    if (!BasicUserPerson.getInstance().getPhone().equals("null") && !BasicUserPerson.getInstance().getPhone().equals("")){
        String tel = BasicUserPerson.getInstance().getPhone().replace("(", "").replace(")", "").replace(" ", "");
        ddd2.setText(tel.subSequence(0, 2));
        telefone.setText(tel.substring(2));
    }
    if (!BasicUserPerson.getInstance().getBirthday().equals("null") && !BasicUserPerson.getInstance().getBirthday().equals("")){
        birthday.setText(BasicUserPerson.getInstance().getBirthday());
    }
    if (!BasicUser.getInstance().locationObj.getZipCode().equals("null") && !BasicUser.getInstance().locationObj.getZipCode().equals("")){
        cep.setText(BasicUser.getInstance().locationObj.getZipCode());         
    }
    if (!BasicUser.getInstance().locationObj.getAddress().equals("null") && !BasicUser.getInstance().locationObj.getAddress().equals("")){
        endereco.setText(BasicUser.getInstance().locationObj.getAddress());         
    }
    if (!BasicUser.getInstance().locationObj.getNeighborhood().equals("null") && !BasicUser.getInstance().locationObj.getNeighborhood().equals("")){
        bairro.setText(BasicUser.getInstance().locationObj.getNeighborhood());         
    }

}

它输出:

  12-15 21:22:55.002: E/AndroidRuntime(2263): FATAL EXCEPTION: main
    12-15 21:22:55.002: E/AndroidRuntime(2263): Process: br.com.inradar, PID: 2263
    12-15 21:22:55.002: E/AndroidRuntime(2263): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.inradar/br.com.inradar.activities.DadosPessoais}: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Handler.dispatchMessage(Handler.java:102)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.os.Looper.loop(Looper.java:136)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.main(ActivityThread.java:5103)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at java.lang.reflect.Method.invoke(Method.java:515)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at dalvik.system.NativeStart.main(Native Method)
    12-15 21:22:55.002: E/AndroidRuntime(2263): Caused by: java.lang.NullPointerException
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at br.com.inradar.activities.DadosPessoais.onCreate(DadosPessoais.java:176)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Activity.performCreate(Activity.java:5275)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
    12-15 21:22:55.002: E/AndroidRuntime(2263):     ... 11 more

1 个答案:

答案 0 :(得分:1)

你是否以这种方式使用

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
    if(resultCode == RESULT_OK) {
          // stub here
          }
        }
       }