我有下一个问题:
当我尝试启动相机时,我可以拍照,甚至将其保存在我的SD卡上,但是当我要在我的设备上显示它的路径时,我会收到错误。
我的全局变量是2(我使用1但是2更好,以确保它是一个奇怪的错误):
private File photofile;
private Uri mMakePhotoUri;
这是我的启动相机功能:
@SuppressLint("SimpleDateFormat")
public void farefoto(int num){
// For naming the picture
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String n = sdf.format(new Date());
String fotoname = "Immagine-"+ n +".jpg";
//Going through files and folders
File photostorage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File photostorage2 = new File(photostorage, "Immagini");
System.out.println(photostorage+"\n"+photostorage2);
photostorage2.mkdirs();
// My file (global)
photofile = new File(photostorage2, fotoname);
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //intent to start camera
// My URI (global)
mMakePhotoUri = Uri.fromFile(photofile);
new Bundle(); // I took this code from internet, but if I remove this line, it's the same
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, num); //num would be 1 on calling function
}
和我的活动结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1){
try{ // tring my global URI
photo = f.decodeAndResizeFile(new File(mMakePhotoUri.getPath()));
}
catch(NullPointerException ex){
System.out.println("fail");
ex.printStackTrace();
try{ // Trying my global FILE
photo = BitmapFactory.decodeFile(photofile.getAbsolutePath());
} catch (Exception e){
e.printStackTrace();
Toast.makeText(this, "C'è stato un errore. Riprova a scattare la foto.", Toast.LENGTH_LONG).show();
}
......
......
.......
}
始终获取NullPointerException
但是...... 如果我再次拍照,那就行了!! 。
我已经阅读了我能在这里找到的一切......但是当我修改一个全局变量并且我再也无法接受它时,它没有逻辑......
提前致谢。 欢呼声。
正如Alex Cohn所说的,我的问题是我在onCreate
之前调用了onActivityResult
,因为可能已经没有内存(因为有时候没有这样做),所以我想要让我的应用程序“健康”,我尝试了一些try / catch
,所以即使它在第一次调用时调用onCreate
或onActivityResult
,我也会得到数据,并且我在Bundle中写了这些数据如restoring our state。
谢谢!
答案 0 :(得分:2)
启动ACTION_IMAGE_CAPTURE
可能会导致您的活动内存不足。您应该检查(我只是一个日志,调试器可能有其自身的副作用),onCreate()
之前调用您的onActivityResult()
活动。如果是这种情况,您应该准备好您的活动以重新初始化自己,可能使用onSaveInstanceState(Bundle)
。
请注意,决定是关闭活动还是将其保留在后台,取决于您无法控制的整体系统状态。如果你拍摄第一张照片的决定是“让他失望的话”,我不会感到惊讶,但是当你再次拍照时,就是“让他留在后台”。
答案 1 :(得分:0)
它不会破坏变量。但经过这么多天的研究LOL,我得到了一个解决我错误的方法。 当我调试调试器时,方法会在拍照后调用它。
通过将这些以下行放在清单中来修复它。这是由于相机配置的变化而发生的。窗口软输入模式。
<activity
android:name="packageName.Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" >