Search code examples
androidandroid-intentandroid-gallery

Getting Image from gallery in android


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);
    }

Solution

  • 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.