3

I am creating an app to upload image to server. I am getting following exception while selecting the image.

Method threw 'android.database.sqlite.SQLiteException' exception..

near "FROM": syntax error (code 1): , while compiling: SELECT  FROM images WHERE (_id=?)

Code to open Gallery :

  Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, IMAGE_PICKER);

On Activity Result

  Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Rahul Giradkar
  • 1,818
  • 1
  • 17
  • 28

2 Answers2

4

When you select any images using ContentProvider, you got is URI of that image. You need to convert this URI to *Absolute Path*:

You can convert URI of any file to absolute path using below util:

public class RealPathUtil {

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

         // Split at colon, use second item in the array
         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);
    }
}

for more information, Please check tutorial here.

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
  • 1
    This has never worked reliably and will fail on all Android 10+ devices. – CommonsWare Jul 15 '19 at 10:54
  • @CommonsWare Can you provide a reliable solution for all devices? – sak Aug 01 '20 at 15:15
  • @sak: There is none. Use the `Uri` itself. See [this](https://stackoverflow.com/a/56308643/115145) and [this](https://stackoverflow.com/questions/59123162/android-kotlin-getting-a-filenotfoundexception-with-filename-chosen-from-file-p) and [this](https://stackoverflow.com/questions/62653207/android-10-bitmapfactory-decodefileimagefilepath-return-null) and [this](https://stackoverflow.com/a/59911702/115145) and countless others. – CommonsWare Aug 01 '20 at 15:49
-1
         if (checkCallingOrSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                                    Intent i = new Intent(Intent.ACTION_PICK,
                                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(i, SELECT_PICTURE);
                                } else {
                                    requestMultiplePermissions();
                                }

        @TargetApi(Build.VERSION_CODES.M)
            public void requestMultiplePermissions() {

                String camera_permission = Manifest.permission.CAMERA;
                int hascampermission = checkSelfPermission(camera_permission);

                String storage_permission_group = Manifest.permission.READ_EXTERNAL_STORAGE;
                int hasStoragePermission = checkSelfPermission(storage_permission_group);

                String storage_writepermission_group = Manifest.permission.WRITE_EXTERNAL_STORAGE;
                int hasstroage = checkSelfPermission(storage_permission_group);

                List<String> permissions = new ArrayList<String>();

                if (hasStoragePermission != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(storage_permission_group);
                }
                if (hascampermission != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(camera_permission);
                }

                if (hasstroage != PackageManager.PERMISSION_GRANTED) {
                    permissions.add(storage_writepermission_group);
                }

                if (!permissions.isEmpty()) {
                    String[] params = permissions.toArray(new String[permissions.size()]);
                    requestPermissions(params, REQUEST_PERMISSIONS);
                }

            }


            @Override
            public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
                switch (requestCode) {
                    case REQUEST_PERMISSIONS:
                        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                        }
                        break;
                    default:
                        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                }
            }


      @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            try {
                if (resultCode == Activity.RESULT_OK) {
                    if (requestCode == SELECT_PICTURE) {
                        Uri selectedImage = data.getData();
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};

                        Cursor cursor = getContentResolver().query(
                                selectedImage, filePathColumn, null, null, null);
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        filePath = cursor.getString(columnIndex);
                        cursor.close();


                        bitmapUser = BitmapFactory.decodeFile(filePath);
                      //  ivprofilepic.setImageBitmap(bitmapUser);

                      //  ivprofilepic.buildDrawingCache();
                    //    bmap = ivprofilepic.getDrawingCache();


                        if (selectedImagePath == null) {
                            // 2:OI FILE Manager --- call method: uri.getPath()
                            selectedImagePath = selectedImage.getPath();
                        }

                        if (selectedImagePath != null) {
                            bitmapUser = decodeSampledBitmapFromResource(selectedImagePath, 600, 600); *//* BitMap from here*//*

                            if (bitmapUser != null) {
                                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                bitmapUser.compress(Bitmap.CompressFormat.JPEG, 95, byteArrayOutputStream);


                                byte[] bsUserImage = byteArrayOutputStream.toByteArray();
                                //                    byteSelectedNewKidImagePath = Base64.encodeBytes(bsUserImage);
                            }

                        }
                    }  

else if (resultCode == Activity.RESULT_CANCELED) {
                    Toast.makeText(getApplicationContext(), " " + getResources().getString(R.string.str_cancelled), Toast.LENGTH_LONG).show();
                } else if (resultCode != Activity.RESULT_CANCELED) {
                    if (requestCode == CAMERA_REQUEST) {
                        bitmapUser = (Bitmap) data.getExtras().get("data");
                      //  ivprofilepic.setImageBitmap(bitmapUser);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

        public String getPath(Uri uri) {
            if (uri == null) {
                return null;
            }

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

            Cursor cursor;
            if (Build.VERSION.SDK_INT > 19) {
                // Will return "image:x*"
                String wholeID = DocumentsContract.getDocumentId(uri);
                // Split at colon, use second item in the array
                String id = wholeID.split(":")[1];
                // where id is equal to
                String sel = MediaStore.Images.Media._ID + "=?";

                cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        projection, sel, new String[]{id}, null);
            } else {
                cursor = getContentResolver().query(uri, projection, null, null, null);
            }
            String path = null;
            try {
                int column_index = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                path = cursor.getString(column_index).toString();
                cursor.close();
            } catch (NullPointerException e) {

            }
            return path;
        }

        public File filepath(int type) {
            File mediaStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    IMAGE_DIRECTORY_NAME);
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {

                }
            }
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                    Locale.getDefault()).format(new Date());
            File mediaFile;
            if (type == MEDIA_TYPE_IMAGE) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator
                        + "IMG_" + timeStamp + ".jpg");

            } else if (type == MEIDA_TYPE_GALARY) {
                mediaFile = new File(mediaStorageDir.getPath() + File.separator
                        + "GAL_" + timeStamp + ".jpg");
            } else {
                mediaFile = null;
            }
            return mediaFile;
        }

        public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            try {
                BitmapFactory.decodeFile(path, options);
                options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
                options.inJustDecodeBounds = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return BitmapFactory.decodeFile(path, options);
        }

        public static int calculateInSampleSize(
                BitmapFactory.Options options, int reqWidth, int reqHeight) {
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
            if (height > reqHeight || width > reqWidth) {
                final int heightRatio = Math.round((float) height / (float) reqHeight);
                final int widthRatio = Math.round((float) width / (float) reqWidth);
                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
            return inSampleSize;
        }
PRATEEK BHARDWAJ
  • 2,364
  • 2
  • 21
  • 35
  • `READ_EXTERNAL_STORAGE` is not required if you have `WRITE_EXTERNAL_STORAGE` since it includes the read permission (https://stackoverflow.com/a/11942464/876086) – Täg Jun 28 '19 at 17:48