2016-11-26 118 views
1

我試圖在我的設備的相機中拍照時,當我調用處理圖像捕獲的方法時,應用程序因爲空指針異常而崩潰。我不知道我的FileProvider丟失了什麼信息,因爲stacktrace將空指針指向我的FileProvider.getUriForFile語句。FileProvider.getUriForFile返回null

這裏是我的代碼 HomeActivity

public void takePhoto(View view){ 
     //camera stuff 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); 

     //folder stuff 
     File imagesFolder = new File(Environment.getExternalStorageDirectory(), "AnimEncylopedia"); 
     if(!imagesFolder.exists()) { 
      imagesFolder.mkdirs(); 
     } 

     File image = new File(imagesFolder, "QR_" + timeStamp + ".png"); 


Uri uriSavedImage = FileProvider.getUriForFile(HomeActivity.this, "com.encyclopedia.fileprovider", image); 

     intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); 
     startActivityForResult(intent, 1); 
    } 

AndroidManifest

<provider 
      android:authorities="com.encyclopedia.fileprovider" 
      android:name="android.support.v4.content.FileProvider" 
      android:exported="false" 
      android:grantUriPermissions="true"> 

      <meta-data 
       android:name="android.support.FILE_PROVIDER_PATHS" 
       android:resource="@xml/file_paths"/> 

     </provider> 

Files_path.xml

<?xml version="1.0" encoding="utf-8"?> 
<paths xmlns:android="http://schemas.android.com/apk/res/android"> 
    <external-path name="my_images" path="Encyclopedia/"/> 
</paths> 

我怎樣才能解決這個問題?

回答

0

使用相機意圖

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(intent, REQUEST_CAMERA); 

onActivityResult()

Bitmap photo = (Bitmap) data.getExtras().get("data"); 

Uri tempUri = getImageUri(getActivity(), photo); 

這也取決於用戶使用的相機應用。與Android相機它會工作正常。但對於其他應用程序,這取決於它們是否返回有效的數據值。