2017-02-20 153 views
1

我正在創建一個將圖像上載到服務器的應用程序。 我在選擇圖像時出現以下異常。如何從圖庫中獲取所選圖像的路徑

方法拋出 'android.database.sqlite.SQLiteException' 例外..

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

代碼以打開圖庫:

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

在活動結果

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)); 
+0

https://stackoverflow.com/a/41141236/115145 – CommonsWare

回答

2

當您選擇使用ContentProvider的任何圖像,你得到的是該圖像的URI。您需要將此URI轉換爲*Absolute Path*

您可以使用下面的util轉換URI的任何文件到absolute path

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

瞭解更多信息,請查看教程here

-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; 
     } 
相關問題