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\'
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.
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;
}