当我使用Capture Image from Camera and Display in Activity和https://developer.android.com/training/camera/photobasics.html
中的一些代码时,我遇到了问题首先,这是在MainActivity.java中。当用户按下按钮" snap"
时,我创建onClickevent Button snap = (Button) findViewById(R.id.button3);
snap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent start_cam = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File path = null;
try {
path = createImageFile();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
if(path!=null) {
start_cam.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(path));
startActivityForResult(start_cam, 1);
}
}
});
接下来,我添加了createImageFile()方法
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
root_file = "file:" + image.getAbsolutePath();
return image;
}
最后一部分,我添加了onActivityResult()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
try {
m = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(root_file));
try {
view.setImageBitmap(m);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我还在AndroidManifest.xml中添加了标题
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
之后,我在Android模拟器API19 Nexus_one API19中使用此功能(拍照)。出现对话框并说出&#34; java.lang.nullPointerException&#34;。
我不知道为什么会出现这个问题。我想它可能是我的模拟器或代码。