[英]Android ContentResolver.insert() throws NullPointerException
[英]Android ContentResolver.insert crashes with “unable to create new file”
我在活動的某些功能中有一個代碼:
ContentValues cv = new ContentValues();
cv.put(MediaStore.Images.Media.TITLE, "1354213408296.jpg");
ContentResolver contentResolver = getContentResolver();
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(cameraIntent, 712984419/*Some request code*/);
它崩潰與:
java.lang.IllegalStateException: Unable to create new file:
/mnt/sdcard/DCIM/Camera/1354213408296.jpg at
android.os.Parcel.readException(Parcel.java:1335) at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:182) at
android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:136) at
android.content.ContentProviderProxy.insert(ContentProviderNative.java:415) at
android.content.ContentResolver.insert(ContentResolver.java:730)
崩潰:
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
"1354213408296.jpg"
只是System.currentTimeInMillis() + ".jpg"
,所以它始終是唯一的
清單中提供了android.permission.WRITE_EXTERNAL_STORAGE
這是一些手機的環境規格(我正在使用ACRA來獲得它):
getDataDirectory=/data
getDownloadCacheDirectory=/cache
getExternalStorageAndroidDataDir=/mnt/sdcard/Android/data
getExternalStorageDirectory=/mnt/sdcard
getExternalStorageState=removed
getRootDirectory=/system
getSecureDataDirectory=/data
getSystemSecureDirectory=/data/system
is4GConfig=true
is8GConfig=false
isEncryptedFilesystemEnabled=false
isExternalStorageEmulated=false
isExternalStorageRemovable=true
我該如何防止這種崩潰?
我不確定您要做什么。 您似乎要做的就是嘗試在MediaStore.Images.Media中創建一個僅包含TITLE列的新行。 在標題中插入沒有數據的標題沒有多大意義。
當沒有sdcard時,這似乎只是另一個例外(我只能在非常奇怪的模擬器上重現它,但誰知道呢?)。 肯定會丟失sdcard的情況。 我當前的解決方案如下:
public static Uri getImageFileUri(Context context) throws IOException{
String fullFileName = generateImageFileName(imageName); // a method i have defined
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fullFileName);
return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return Uri.fromFile(new File(fullFileName));
}
}
這是我用來生成Uri
的方法,我將以此開始相機的意圖。 之后,我會像您一樣使用它。 問題是我在no sdcard情況下返回的值無法正常工作,但另一方面,如果不存在sdcard,Android設備將不允許拍照。 使用此解決方案,如果有sdcard,您將成功拍照,在其他情況下,將啟動本機相機,並顯示消息“插入sdcard以便拍照”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.