我正在做一个我需要打开一个图库并选择图片的应用程序,但是当我返回Activity时,项目的Cursor返回null。
在这里我打开画廊:
private static final int SELECT_PICTURE = 1;
private void abrirGaleria(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a pic"), SELECT_PICTURE);
}
在这里我尝试得到结果:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == ((Activity)ctx).RESULT_OK){
Uri selectedImageURI = data.getData();
File filePath = new File(getRealPathFromURI(selectedImageURI));
compartilharAFoto(filePath.getPath());
}
}
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = ((Activity)ctx).getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
//cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(0);//idx);
}
}
和错误:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131073, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:1633 flg=0x1 }} to activity {br.com.blacktoad.q48h2/br.com.blacktoad.q48h2.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
出现的另一个错误说明:
Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
答案 0 :(得分:0)
您的查询没有您尝试访问的列。 替换:
Cursor cursor = ((Activity)ctx).getContentResolver() .query(contentURI, null, null, null, null);
使用:
Cursor cursor = ((Activity)ctx).getContentResolver()
.query(contentURI, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
并按如下方式更新此行:
int idx = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
并取消注释:
cursor.moveToFirst();