我正在尝试使用意图获取图像但是当我选择图像时,我的应用程序立即关闭。 这是我的实际代码:
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);
}
它应该在图像选择后调用onActivityResult
方法,但不幸的是在Logcat中没有任何错误地关闭。
有什么不对吗?
logcat的
答案 0 :(得分:3)
请用{/ p>替换getActivity().startActivityForResult(i, 1);
startActivityForResult(i, 1);
然后在您的片段中覆盖onActivityResult()
,并在您的活动中覆盖
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
并检查断点是否执行中的任何一个。
答案 1 :(得分:2)
首先确保您的目录已创建......
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Folder/";
File newdir = new File(dir);
newdir.mkdirs();
比你的功能
private void capturarFoto() {
String file = dir+DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString()+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("Demo Pic", "Picture is saved");
}
}
}
确保您在清单
中添加权限<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
祝你好运:
答案 2 :(得分:1)
改变这个:
String nameFoto = DateFormat.format("yyyy-MM-dd_hhmmss", new Date()).toString();
getActivity().startActivityForResult(intent, 1);
要:
String nameFoto = new SimpleDateFormat("yyyy-MM-dd_hhmmss").format(new Date());
startActivityForResult(intent, 1);
并确保添加以下权限:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>