Android crash when picking an image from Google drive - android

I made an Gallery Pick Intent.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(galleryIntent, requestCode);
I choose a picture from google drive and return to onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_GALLERY_PICK) {
try {
setAvatar(ImageUtils.getPath(EditClientActivity.this, data.getData(), IMAGE));
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
avatarSizeOriginal = null;
}
}
Here I get the path from selected Image:
public static String getPath(Context ctx, Uri uri, String fileType) {
String mPath = null;
Cursor mCursor;
String[] mColumns = {MediaStore.Images.Media.DATA};
if (uri == null) {
return null;
}
// algorithm to be used for devices starting with KK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String mId = uri.getPathSegments().get(uri.getPathSegments().size() - 1);
String mSelection = "";
Uri mProvider = null;
if (mId.contains(":")) {
final String[] split = mId.split(":");
mId = split[1];
}
if (fileType.equals(FileTypes.IMAGE)) {
mSelection = MediaStore.Images.Media._ID + "=?";
mProvider = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
if (fileType.equals(FileTypes.VIDEO)) {
mSelection = MediaStore.Video.Media._ID + "=?";
mProvider = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
if (fileType.equals(FileTypes.AUDIO)) {
mSelection = MediaStore.Audio.Media._ID + "=?";
mProvider = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
mCursor = ctx.getContentResolver().query(mProvider, mColumns, mSelection, new String[]{mId}, null, null);
} else {
mCursor = ctx.getContentResolver().query(uri, mColumns, null, null, null);
}
int column_index = mCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (mCursor != null && mCursor.moveToFirst()) {
mPath = mCursor.getString(column_index);
mCursor.close();
}
if (mPath==null) {
mPath = uri.getPath();
}
return mPath;
}
And at last when I try to use the image i get a crash:
private void setAvatar(String path) throws IOException {
avatarSizeOriginal = new File(path);
initialAvatar = new File(path);}
It indicates path /document/acc=1;doc=231
How to deal with such issue ?

Related

How to get real path of image to upload server become crash above kitkat

private String getRealPathFromURI(Uri image) {
String[] proj = { MediaStore.Images.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader(
this,
image, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public static String getFilePathByUri(Context context, Uri uri) {
String fileName = "";
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow("_data");
filePathUri = Uri.parse(cursor.getString(column_index));
fileName = filePathUri.getEncodedPath();
}
cursor.close();
} else if (uri.getScheme().compareTo("file") == 0) {
fileName = filePathUri.getEncodedPath();
} else {
fileName = fileName + "_" + filePathUri.getLastPathSegment();
}
return fileName;
}
Try this
private String getRealPathFromURI(String contentURI) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String str = cursor.getString(index);
cursor.close();
return str;
}
}
Check this
#SuppressLint("NewApi")
public static String getRealPathFromURI(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;
}
Get URI from Camera
private Uri capturedUri;
public void openCamera() {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createMediaFile(1);
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
capturedUri = null;
capturedUri = Uri.fromFile(photoFile);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
startActivityForResult(takePicture, 1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if ((null == data) || (data.getData() == null)) {
try {
Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), capturedUri);
img_profileimage.setImageBitmap(photo);
capturedUri = getImageUri(context, photo);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, context.getResources().getString(R.string.some_thing_went_wrong), Toast.LENGTH_SHORT);
}
} else if (requestCode == 2) {
if (data.getData() != null) {
// Uri selectedImage = data.getData();
capturedUri = null;
capturedUri = data.getData();
} else {
Toast.makeText(context, context.getResources().getString(R.string.some_thing_went_wrong), Toast.LENGTH_SHORT);
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String picturePath = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Image", null);
return Uri.parse(picturePath);
}
public File createMediaFile(int type) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = type == 1 ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(type == 1 ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
File file = File.createTempFile(fileName, /* prefix */type == 1 ? ".jpg" : ".mp4",/* suffix */storageDir/* directory */);
return file;
}

Android- Not able to select file from internal storage

I have to get image from internal storage of mobile device and upload to server. If I select image from sdcard it working fine, while if I select image from internal storage it show error, I am not able to get this error.
Here is logcat output -
07-26 10:32:24.868: W/System.err(24051): java.io.FileNotFoundException: /document/primary:Pictures/Screenshots/Screenshot_20160712-172722.png: open failed: ENOENT (No such file or directory)
I am using this code to get image
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
1);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
OnActivityResult code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// 1
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
try {
// SDK < API11
if (Build.VERSION.SDK_INT < 11)
realPath_1 = RealPathUtil
.getRealPathFromURI_BelowAPI11(getActivity(),
data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath_1 = RealPathUtil.getRealPathFromURI_API11to18(
getActivity(), data.getData());
// SDK > 19 (Android 4.4)
else
realPath_1 = RealPathUtil.getRealPathFromURI_API19(
getActivity(), data.getData());
Log.e("", "Build Version : " + Build.VERSION.SDK_INT);
Log.e("", "Get Data Get Path : " + data.getData().getPath());
if (realPath_1.equalsIgnoreCase("")) {
realPath_1 = data.getData().getPath().toString();
}
Log.e("", "Real Path 1 : " + realPath_1);
file_1 = realPath_1.substring(
realPath_1.lastIndexOf('/') + 1,
realPath_1.length());
Log.i("File Name 1 ", file_1);
txt_file_name_1.setText(file_1);
} catch (Exception e) {
Uri selected = data.getData();
realPath_1 = selected.getPath();
file_1 = realPath_1.substring(
realPath_1.lastIndexOf('/') + 1,
realPath_1.length());
Log.i("File Name 1 ", file_1);
txt_file_name_1.setText(file_1);
}
}
}}
Here is class named - RealPathUtil to get path of images.
My
android:minSdkVersion="14"
android:targetSdkVersion="23"
and called this method from class RealPathUtil
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;
}
Please help and thanks in advance.
Try this:
boolean isKitKat = false;
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
Code for show file chooser function
private void showFileChooser() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
isKitKat = true;
startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
} else {
isKitKat = false;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
}
}
OnActivity Result code :
#TargetApi(19)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (data != null && data.getData() != null && resultCode == getActivity().RESULT_OK) {
boolean isImageFromGoogleDrive = false;
Uri uri = data.getData();
if (isKitKat && DocumentsContract.isDocumentUri(getActivity(), uri)) {
if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
realPath_1 = Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
Pattern DIR_SEPORATOR = Pattern.compile("/");
Set<String> rv = new HashSet<>();
String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
if (TextUtils.isEmpty(rawExternalStorage)) {
rv.add("/storage/sdcard0");
} else {
rv.add(rawExternalStorage);
}
} else {
String rawUserId;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
rawUserId = "";
} else {
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String[] folders = DIR_SEPORATOR.split(path);
String lastFolder = folders[folders.length - 1];
boolean isDigit = false;
try {
Integer.valueOf(lastFolder);
isDigit = true;
} catch (NumberFormatException ignored) {
}
rawUserId = isDigit ? lastFolder : "";
}
if (TextUtils.isEmpty(rawUserId)) {
rv.add(rawEmulatedStorageTarget);
} else {
rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
}
}
if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
Collections.addAll(rv, rawSecondaryStorages);
}
String[] temp = rv.toArray(new String[rv.size()]);
for (int i = 0; i < temp.length; i++) {
File tempf = new File(temp[i] + "/" + split[1]);
if (tempf.exists()) {
realPath_1 = temp[i] + "/" + split[1];
}
}
}
} else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
String id = DocumentsContract.getDocumentId(uri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = getActivity().getContentResolver().query(contentUri, projection, null, null,
null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
realPath_1 = cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
} else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = "_id=?";
String[] selectionArgs = new String[]{split[1]};
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = getActivity().getContentResolver().query(contentUri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
realPath_1 = cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
} else if ("com.google.android.apps.docs.storage".equals(uri.getAuthority())) {
isImageFromGoogleDrive = true;
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
Cursor cursor = null;
String column = "_data";
String[] projection = {column};
try {
cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(column);
realPath_1 = cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
realPath_1 = uri.getPath();
}
try {
Log.d(TAG, "Real Path 1 : " + realPath_1);
file_1 = realPath_1.substring(realPath_1.lastIndexOf('/') + 1, realPath_1.length());
Log.i("File Name 1 ", file_1);
} catch (Exception e) {
e.printStackTrace();
}
}
}}
Here file_1 = get image name and realPath_1 show full path of image from internal or external storage.
Happy to help :)
Use bellow code for get file URL.
public static String getPath(final Context context, final Uri uri) {
// check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] { split[1] };
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
Your code looks fine you just have to get runtime permissions from user. In Andorid 6.0 or later needs permission from user at runtime only declaring them manifest is not enough.
See here my earlier post about how to get runtime permissions.
Update:
private void showFileChooser() {
try {
// Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// startActivityForResult(i, RESULT_LOAD_IMAGE);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, RESULT_LOAD_IMAGE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getActivity(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
//Uri selectedImage = data.getData();
txt_file_name_1.setText(data.getData().toString());
}
}

get path of video file selected from gallery getting NULL. How to get path of video file?

get path of video file selected from gallery getting NULL. How to get path of video file ? Get URi in Activity Result also give null. converting Uri to String also getting Null.
Intent intent;
String selectedVideo1Path, selectedVideo2Path;
EditText e1,e2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_activity);
Button button1 = (Button) findViewById(R.id.video1_btn);
Button button2 = (Button) findViewById(R.id.video2_btn);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 101);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 102);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (data.getData() != null) {
selectedVideo1Path = getPath(data.getData());
Toast.makeText(MergeVideosActivity.this, "Path 1 : "+selectedVideo1Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
if (requestCode == 102) {
if (data.getData() != null) {
selectedVideo2Path = getPath(data.getData());
//String str2 = selectedVideo2Path.toString();
// e2.setText(str2);
Toast.makeText(MergeVideosActivity.this, "Path 2 : "+selectedVideo2Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
}
This is my getPath method
public String getPath(Uri uri) {
int column_index = 0;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
}
return cursor.getString(column_index);
}
Selected Video from Gallery I hope its OK ? Check it
public void selectVideoFromGallery() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
} else {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI);
}
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
}
}
Update your getPath method
public String generatePath(Uri uri,Context context) {
String filePath = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat){
filePath = generateFromKitkat(uri,context);
}
if(filePath != null){
return filePath;
}
Cursor cursor = context.getContentResolver().query(uri, new String[] { MediaStore.MediaColumns.DATA }, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath == null ? uri.getPath() : filePath;
}
#TargetApi(19)
private String generateFromKitkat(Uri uri,Context context){
String filePath = null;
if(DocumentsContract.isDocumentUri(context, uri)){
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { Media.DATA };
String sel = Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(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;
}

move image from one folder to another in android sdcard

In my project I'm selecting image from the gallery and want to move it from gallery to some other folder in my sdcard .... so far I have done selecting the image and the path of the image is also got... now I have to move that image from that folder....
thanks in advance
MainActivity
public class MainActivity extends ActionBarActivity {
ImageView iv;
Button load,cp;
TextView tv,tvpath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView)findViewById(R.id.imageView);
tv = (TextView)findViewById(R.id.textView);
tvpath = (TextView)findViewById(R.id.textView2);
load = (Button)findViewById(R.id.button);
cp = (Button)findViewById(R.id.button2);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
startActivityForResult(i, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode== 1 && resultCode == RESULT_OK && data != null){
String realpath;
if (Build.VERSION.SDK_INT < 11){
realpath = RealPathUtil.getRealPathFromURI_BelowAPI11(this,data.getData());
}else if (Build.VERSION.SDK_INT < 19){
realpath = RealPathUtil.getRealPathFromURI_BelowAPI11to18(this, data.getData());
}else{
realpath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
}
settext(Build.VERSION.SDK_INT,data.getData().getPath(),realpath);
changepath(realpath);
/* Uri pickimage = data.getData();
String[] filepath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickimage,filepath,null,null,null);
cursor.moveToFirst();
String imgpath = cursor.getString(cursor.getColumnIndex(filepath[0]));
iv.setImageBitmap(BitmapFactory.decodeFile(imgpath));
cursor.close();
Toast.makeText(getApplicationContext(),filepath[0],Toast.LENGTH_SHORT).show();
*/
}
}
//tried to chage the path here
private void changepath(String realpath) {
File rp = new File(realpath);
File cp = new File("/mnt/sdcard/myapp/");
rp.renameTo(cp);
String s = rp.getAbsolutePath();
Toast.makeText(getApplicationContext(),"new path is:"+s,Toast.LENGTH_LONG).show();
}
private void settext(int sdkInt, String path, String realpath) {
this.tv.setText("uri path :"+path);
this.tvpath.setText("Real path :"+realpath);
Uri uri = Uri.fromFile(new File(realpath));
iv.setImageURI(uri);
}
}
**RealPathUtil**
public class RealPathUtil {
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);
}
public static String getRealPathFromURI_BelowAPI11to18(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_API19(Context context, Uri data) {
String filepath = "";
String wholeID = DocumentsContract.getDocumentId(data);
String[] column = {MediaStore.Images.Media.DATA};
String sel = MediaStore.Images.Media._ID + "=?";
String id = wholeID.split(":")[1];
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;
}
}
Make sure you have the permission to write to files. You do that by putting this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
in your AndroidManifest.xml
If your method to move bitmaps fail you can try this method:
path_source is the path of the bitmap and path_destination is the new path. (where you want to move your bitmap)
public static void MoveFile(String path_source, String path_destination) throws IOException {
File file_Source = new File(path_source);
File file_Destination = new File(path_destination);
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(file_Source).getChannel();
destination = new FileOutputStream(file_Destination).getChannel();
long count = 0;
long size = source.size();
while((count += destination.transferFrom(source, count, size-count))<size);
file_Source.delete();
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}

Xamarin Choose Image From Gallery Path is Null

using this recipe to try and choose an image from the gallery and then upload it to s3 but
my path always returns null.
private string _imgPath;
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
public string GetImage()
{
InitializeMediaPicker();
return _imgPath;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) return;
var uri = data.Data;
_imgPath = GetPathToImage(uri);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string path = null;
// The projection contains the columns we want to return in our query.
var projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (var cursor = ManagedQuery(uri, projection, null, null, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
Here is a working implementation ported from this question and specifically, this answer.
Include the WRITE_EXTERNAL_STORAGE permission in your manifest for this code to work.
public delegate void OnImageResultHandler(bool success, string imagePath);
protected OnImageResultHandler _imagePickerCallback;
public void GetImage(OnImageResultHandler callback)
{
if (callback == null) {
throw new ArgumentException ("OnImageResultHandler callback cannot be null.");
}
_imagePickerCallback = callback;
InitializeMediaPicker();
}
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) {
return;
}
string imagePath = null;
var uri = data.Data;
try {
imagePath = GetPathToImage(uri);
} catch (Exception ex) {
// Failed for some reason.
}
_imagePickerCallback (imagePath != null, imagePath);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string doc_id = "";
using (var c1 = ContentResolver.Query (uri, null, null, null, null)) {
c1.MoveToFirst ();
String document_id = c1.GetString (0);
doc_id = document_id.Substring (document_id.LastIndexOf (":") + 1);
}
string path = null;
// The projection contains the columns we want to return in our query.
string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
using (var cursor = ManagedQuery(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {doc_id}, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
Example Usage:
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
GetImage(((b, p) => {
Toast.MakeText(this, "Found path: " + p, ToastLength.Long).Show();
}));
};
I've used a callback instead of returning the path for GetImage as the calling method would finish executing before OnActivityResult is called so the path returned would never be valid.
I changed the GetPathToImage method from the Xamarin recipe to the code below and now it works!
private string GetPathToImage(Android.Net.Uri uri)
{
ICursor cursor = this.ContentResolver.Query(uri, null, null, null, null);
cursor.MoveToFirst();
string document_id = cursor.GetString(0);
document_id = document_id.Split(':')[1];
cursor.Close();
cursor = ContentResolver.Query(
Android.Provider.MediaStore.Images.Media.ExternalContentUri,
null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new String[] { document_id }, null);
cursor.MoveToFirst();
string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
cursor.Close();
return path;
}

Categories

Resources