我有下一个问题:
当我尝试启动相机时,我可以拍摄照片,甚至将其保存在sdcard上,但是当我准备在设备上显示该照片的路径时,会出现错误。
我的全局变量为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中,如恢复状态的链接中所述。
谢谢!。