3

I've been trying to get an image from gallery in this app and then on a button click I want to upload to my PHP server.

The "selectedImagePath" comes as null why? If anyone has a solutions please help me! Thanks in advance.

onCreate()

img = (ImageView) findViewById(R.id.ImageView01);
        Button browse = (Button) findViewById(R.id.Button01);

        browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            }
        });

onActivityResult()

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                selectedImageUri = data.getData();
                System.out.println(selectedImageUri);
                selectedImagePath = getPath(selectedImageUri);//returns as null
                System.out.println("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri);
            }
        }
    }

getPath()

public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
BrijD
  • 103
  • 1
  • 2
  • 10
  • Where is your `getPath()` method? Have you added `write and read external storage` permission to manifest file? – Piyush Jan 30 '15 at 05:08

5 Answers5

9

try this

@Override
public void onClick(View view) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivityForResult(intent, 0);
}

@Override
 protected void onActivityResult(int reqCode, int resCode, Intent data) {
    if(resCode == Activity.RESULT_OK && data != null){
        String realPath;
        // SDK < API11
        if (Build.VERSION.SDK_INT < 11) {
            realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
        }

        // SDK >= 11 && SDK < 19
        else if (Build.VERSION.SDK_INT < 19) {
            realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
        }

        // SDK > 19 (Android 4.4)
        else {
            realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
        }
        System.out.println("Image Path : " + realPath);
    }
}


public class RealPathUtil {

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API19(Context context, Uri uri){
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);

         String id = wholeID.split(":")[1];

         String[] column = { MediaStore.Images.Media.DATA };     

         // where id is equal to             
         String sel = MediaStore.Images.Media._ID + "=?";

         Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                                   column, sel, new String[]{ id }, null);

         int columnIndex = cursor.getColumnIndex(column[0]);

         if (cursor.moveToFirst()) {
             filePath = cursor.getString(columnIndex);
         }   
         cursor.close();
         return filePath;
    }


    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
          String[] proj = { MediaStore.Images.Media.DATA };
          String result = null;

          CursorLoader cursorLoader = new CursorLoader(
                  context, 
            contentUri, proj, null, null, null);        
          Cursor cursor = cursorLoader.loadInBackground();

          if(cursor != null){
           int column_index = 
             cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           result = cursor.getString(column_index);
          }
          return result;  
    }

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
               String[] proj = { MediaStore.Images.Media.DATA };
               Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
               int column_index
          = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
               cursor.moveToFirst();
               return cursor.getString(column_index);
    }
}

the code for getRealPath class is not mine, I din't write down the website.

Cristian Olaru
  • 487
  • 5
  • 20
0

When you get the data, create file from that path first and then get that file's path as "selectedImagePath". Then you will get actual path of image on external storage: Try below code:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            selectedImageUri = data.getData();
            File myFile = new File(selectedImageUri);
            System.out.println(selectedImageUri);
            selectedImagePath = myFile.getPath();
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }
    }
}
Pankaj Deshpande
  • 502
  • 2
  • 5
  • 15
0

try this code,

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            System.out.println("Image Path : " + selectedImagePath);
            img.setImageURI(selectedImageUri);
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
Ashok Kateshiya
  • 659
  • 4
  • 10
0

Try below code

if (resultCode == RESULT_OK) {
    if (requestCode == SELECT_PICTURE) {
            Uri uri = data.getData();
            String[] filepath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(uri, filepath, null,
                    null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filepath[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            System.out.println("Image Path : " + filePath);

        }
Ramesh
  • 526
  • 3
  • 14
0

I've spent some time on this problem and eventually I found the fully working solution().

A. It's taken from cordova-plugin-camera which can be found here:

public static String getRealPath(final Uri uri, final Context context) {
    String realPath = null;

    if (Build.VERSION.SDK_INT < 11) {
        realPath = FileHelper.getRealPathFromURI_BelowAPI11(context, uri);

        // SDK >= 11
    } else {
        realPath = FileHelper.getRealPathFromURI_API11_And_Above(context, uri);
    }

    return realPath;
}

both methods are provided in [FileHelper.class]: https://github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java

I don't want to duplicate the code, links are provided instead because solutions are quite complex. /I consider the fact that they could expire but hoping they won't/

B. Here is a link to the source code of a sample project [RealPathUtil.java]: https://github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/hmkcode/android/image/RealPathUtil.java

C. Another question in here that didn't find much attention. [Stack Overflow Post]: https://stackoverflow.com/a/36714242

Community
  • 1
  • 1
Pavlik
  • 141
  • 1
  • 5