问题描述
- camera activity报错空指针异常
-
camera intent:fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
这部分报空指针异常的错误,谁能解释一下为什么,还有需要改什么地方?
button_1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // 创建一个文件来保存图像 intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); //设置图像的文件名 startActivityForResult(intent, TAKE_PICTURE); } }); protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) { if (resultCode == RESULT_OK) { // 获取图像,保存在 Intent中fileUri里 Toast.makeText(this, "Image saved to:n" + data.getData(), Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { // 用户取消图像获取 } else { // 图像获取失败 } } }
解决方案
//创建拍照 Intent并将控制权返回给调用的程序
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
//创建保存图片的文件
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
你把Intent这样初始化一下看看
解决方案二:
应该是fileUri的问题
你试着这样改下
fileUri=Uri.fromFile(new File(Environment .getExternalStorageDirectory(), "temp.jpg"))
解决方案三:
试一下这个方法:
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//你保存图像的url
}
时间: 2024-10-03 10:19:19