我有一个选择图像的Android应用程序。文件uri正确获取。
RequestBody requestFile=null;
File file=null;
String filePath=getPath(fileUri).trim(); // getting same filepath choosing via gallery or other file manager
if (fileUri!= null )
try{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
file = FileUtils.getFile(getActivity(),fileUri); // neglect this line Iam using api below 19
else {
file=new File(filePath); // TODO: 30-Mar-17 CORRECT THE ERROR FOR API BELOW 19
}
String haaii="sdf";
String g=file.getAbsolutePath(); //excecuting when choosing file manager.
requestFile = RequestBody.create(
MediaType.parse(context.getContentResolver().getType(fileUri)),
file
); // weired not excecuting..null pointer expet choosing via gallery
}catch (Exception e){
Log.e("multipart",e.toString());
}
else Log.e("fileuri","uri is null");
路径方法
public String getPath(Uri uri) {
String path = null;
String[] projection = { MediaStore.Files.FileColumns.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if(cursor == null){
path = uri.getPath();
}
else{
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(column_index);
cursor.close();
}
return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
}
选择文件
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
使用
获得结果@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
photo.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
E/multipart: java.lang.NullPointerException
通过画廊选择-ok
但错误很奇怪。通过画廊选择时,没关系。但是当使用文件管理器获取空指针异常时。但是,当通过文件管理器或库选择时,字符串值filePath
是相同的。 如何解决这个问题?但是当我删除try catch块时,没有显示空指针异常,但下一行没有执行..