我的应用程序中有一些代码可以很好地打开图库(从我的应用程序中)、选择照片并上传。
我已经做了一个公平的尝试,将对带有附加 EXTRA_STREAM 的 Intent 的处理集成在一起,例如由图库中的“共享”按钮生成的 Intent 。
这适用于我的 Droid X,也适用于模拟器。
今天,我收到一个用户的错误报告;当我要求它向我返回 EXTRA_STREAM 参数中引用的资源时,我用来将照片从 MediaStore 中拉出的光标返回 null。代码已经通过验证 Intent 附加了 EXTRA_STREAM 的点,用户告诉我他们正在使用库中的“共享”选项。
他们的设备是:
操作系统版本:2.3.3(10/GRI40) 设备:HTC PG86100
什么给了?
为什么 HTC 画廊会向我发送一个带有我无法访问的 EXTRA_STREAM 的 Intent?
是否还有其他原因导致游标返回 null?
String[] filePathColumn = {MediaColumns.DATA};
Uri selectedImageUri;
//Selected image returned from another activity
if(fromData){
selectedImageUri = imageReturnedIntent.getData();
} else {
//Selected image returned from SEND intent
// This is the case that I'm having a problem with.
// fromData is set in the code that calls this;
// false if we've been called from an Intent that has an
// EXTRA_STREAM
selectedImageUri = (Uri)getIntent().getExtras().get(Intent.EXTRA_STREAM);
}
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst(); // <-- NPE on this line
最佳答案
事实证明,许多应用程序将发送带有 image/* mime 类型的 EXTRA_STREAM,但并非所有应用程序都使用图库的内容提供程序。
生成空指针异常(如上)的情况是当我收到一个文件时试图从内容提供者读取://EXTRA_STREAM。
工作代码如下:
String filePath;
String scheme = selectedImageUri.getScheme();
if(scheme.equals("content")){
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst(); // <--no more NPE
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
} else if(scheme.equals("file")){
filePath = selectedImageUri.getPath();
Log.d(App.TAG,"Loading file " + filePath);
} else {
Log.d(App.TAG,"Failed to load URI " + selectedImageUri.toString());
return false;
}
关于Android 图库 "share via"和 Intent.EXTRA_STREAM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6852426/