我有一个应用程序,可以在其中打开相机并拍照并保存图片。当我单击按钮打开相机时,它的工作原理。如果我不拍照就单击手机上的后退按钮,则我的应用程序将停止。我该如何解决这个问题?
Button camera = (Button) findViewById(R.id.camer);
camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(Intent.ACTION_SEND);
//Log.d("URI@!@#!#!@##!", Uri.fromFile(pic).toString() + " " + pic.exists());
if (pic != null) {
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
}
i.setType("image/jpg");
startActivity(Intent.createChooser(i, "Share you on the jobing"));
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
image = (ImageView) findViewById(R.id.imageToUpload);
image.setImageBitmap(thumbnail);
try {
File root = Environment.getDataDirectory();
if (root.canWrite()) {
pic = new File(root, "pic.jpg");
FileOutputStream out = new FileOutputStream(pic);
thumbnail.compress(CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}
由于:java.lang.NullPointerException:尝试调用虚拟 方法'android.os.Bundle android.content.Intent.getExtras()'在 空对象引用
答案 0 :(得分:0)
这是因为您的data
为空
尝试这种方式:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAMERA_PIC_REQUEST){
if (resultCode == RESULT_OK) {
thumbnail = (Bitmap) data.getExtras().get("data");
image = (ImageView) findViewById(R.id.imageToUpload);
image.setImageBitmap(thumbnail);
try {
File root = Environment.getDataDirectory();
if (root.canWrite()) {
pic = new File(root, "pic.jpg");
FileOutputStream out = new FileOutputStream(pic);
thumbnail.compress(CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
}
}
答案 1 :(得分:0)
尝试
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
Bitmap thumbnail = (Bitmap)data.getExtras().get("data");
}
}
if (resultCode == RESULT_CANCELED) {
return;
}
}
}