Get filepath and filename of selected gallery image in Android
android, android-gallery, filepath, java
Solution
A little late to the party but here's my code, hope this helps.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData( );
String picturePath = getPath( getActivity( ).getApplicationContext( ), selectedImageUri );
Log.d("Picture Path", picturePath);
}
}
public static String getPath( Context context, Uri uri ) {
String result = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
if(cursor != null){
if ( cursor.moveToFirst( ) ) {
int column_index = cursor.getColumnIndexOrThrow( proj[0] );
result = cursor.getString( column_index );
}
cursor.close( );
}
if(result == null) {
result = "Not found";
}
return result;
}
Problem
I am creating an app which uploads a selected image from the gallery and uploads it to a web service. The webservice requires the filename of selected image plus a base64 encoding of the file contents. I have managed to achieve this with a hardcoded file path. However, I am struggling to get the real filepath of the image. I have read around the web and have this code, but it does not work for me: ``` public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { Uri selectedImageUri = data.getData(); String[] projection = {MediaStore.Images.Media.DATA}; try { Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); Log.d("Picture Path", picturePath); } catch(Exception e) { Log.e("Path Error", e.toString()); } } } ``` I get this error: ``` java.lang.NullPointerException ``` EDIT Forgot to mention I am using Kitkat. It looks like my problem is KitKat related. I found this (see below) which helped me get my app working: Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT