【发布时间】:2014-11-27 13:34:16
【问题描述】:
程序突然停止工作。
我有一个 URI:“content://com.android.providers.media.documents/document/image%3A13”,一个图像的文件路径。
URI 的路径是这样选择的:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
try {
// This bit here
Bitmap bitmap = getPath(data.getData());
Log.i("Bitmap", "Bmp: " + data.getData());
}catch (Exception e){
Log.e("Error", "Error with setting the image.");
e.printStackTrace();
}
}
}
所以,getPath()被调用,将数据作为URI放入(URI是正确的,日志显示)
在getPath():
private Bitmap getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null,null);
cursor.moveToFirst();
// it is this line here, it returns null for some reason.
String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
// Convert file path into bitmap image using below line.
Log.i("File Path", "File name: " + filePath); // this comes out as NULL in the logcat
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
filePathForUpload = filePath;
try {
ExifInterface exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
bitmap = rotateBitmap(bitmap, orientation);
}catch (Exception e){
Log.d("Error", "error with bitmap!");
e.printStackTrace();
}
return bitmap;
}
Logcat 输出:
java.lang.IllegalArgumentException: filename cannot be null
at android.media.ExifInterface.<init>(ExifInterface.java:121)
at build.com.build.SubmitPicActivity.getPath(SubmitPicActivity.java:123)
at build.com.build.SubmitPicActivity.onActivityResult(SubmitPicActivity.java:93)
at android.app.Activity.dispatchActivityResult(Activity.java:5423)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3361)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3408)
at android.app.ActivityThread.access$1300(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
第 123 行是:String filePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
第 93 行是:Bitmap bitmap = getPath(data.getData());
有什么建议吗?
【问题讨论】:
-
private Bitmap getPath(Uri uri)名称错误,因为它返回的不是路径而是位图。最好让它返回filePath。然后制作另一个函数Bitmap bitmap = getBitmap(String path);。使您的代码更具可读性。 -
@greenapps 好建议,谢谢。