move image from one folder to another in android sdcard - android

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

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

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

Select image from gallery for some device it null

i am getting image from gallery from below code
Uri filePath = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.MIME_TYPE};
Cursor cursor =
mCon.getContentResolver().query(filePath, filePathColumn, null, null, null);
but when i select image from file explore in some devices cursor is always null but if i select same image from gallery app it works... why it so ?
try this code
private String uriToFilename(Uri uri) {
String path = null;
if (Build.VERSION.SDK_INT < 11) {
path = RealPathUtil.getRealPathFromURI_BelowAPI11(this, uri);
} else if (Build.VERSION.SDK_INT < 19) {
path = RealPathUtil.getRealPathFromURI_API11to18(this, uri);
} else {
path = RealPathUtil.getRealPathFromURI_API19(this, uri);
}
return path;
}
create RealOathUtil.java
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri) {
Log.e("uri", uri.getPath());
String filePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
Log.e("wholeID", wholeID);
// Split at colon, use second item in the array
String[] splits = wholeID.split(":");
if (splits.length == 2) {
String id = splits[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();
}
} else {
filePath = uri.getPath();
}
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);
}
}
Now in onactivtyResult() use this
Uri selectedImageUri = data.getData();
String selectedImagePath = uriToFilename(selectedImageUri);
You should try this.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Try this code.
To open gallery:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
mImagePath = getPath(selectedImageUri);
mBitmap = BitmapFactory.decodeFile(mImagePath);
mProfilePic.setImageBitmap(mBitmap);
}
}
To get actual path of image:
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Hope this may help you.

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);
}
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.
When you get the data, create file from that path first and then get that file's path as "selectedImagePath". Then you will get actual path of image on external storage: Try below code:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
File myFile = new File(selectedImageUri);
System.out.println(selectedImageUri);
selectedImagePath = myFile.getPath();
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
try this code,
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
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);
}
Try below code
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri uri = data.getData();
String[] filepath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, filepath, null,
null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filepath[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
System.out.println("Image Path : " + filePath);
}
I've spent some time on this problem and eventually I found the fully working solution().
A.
It's taken from cordova-plugin-camera which can be found here:
public static String getRealPath(final Uri uri, final Context context) {
String realPath = null;
if (Build.VERSION.SDK_INT < 11) {
realPath = FileHelper.getRealPathFromURI_BelowAPI11(context, uri);
// SDK >= 11
} else {
realPath = FileHelper.getRealPathFromURI_API11_And_Above(context, uri);
}
return realPath;
}
both methods are provided in [FileHelper.class]:
https://github.com/apache/cordova-plugin-camera/blob/06d609cfa4871b4a2811f5a8f7f0a822733209b9/src/android/FileHelper.java
I don't want to duplicate the code, links are provided instead because solutions are quite complex. /I consider the fact that they could expire but hoping they won't/
B.
Here is a link to the source code of a sample project [RealPathUtil.java]: https://github.com/hmkcode/Android/blob/master/android-show-image-and-path/src/com/hmkcode/android/image/RealPathUtil.java
C.
Another question in here that didn't find much attention. [Stack Overflow Post]: https://stackoverflow.com/a/36714242

how to get Real Path from Uri?

I would like to upload file to server. So I use a file chooser. But I have a problem with some application to get the real path from uri. the case if the content is a v
ideo, audio or image or if I can get the path directly i have no problem. the methode imlemented are :
public String getRealAudioPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Audio.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader(
this,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and it is the some for image and video. but my problem is when content is in this forme:
content://com.dataviz.dxtg.documentprovider/document/file%3A%2F%2F%2Fmnt%2Fsdcard%2FDownload%2Arbres.png
I tried the method
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
So how to get the real path from URi and if there is an other content type .
to get my real path is given below:
//Uri return from external activity
orgUri = data.getData();
text1.setText("fichier à envoyer " + orgUri.toString() + "\n");
// imagepath = orgUri.toString() ;
//path converted from Uri
//convertedPath = orgUri.getPath();
if(orgUri.toString().contains(IMAGEMEDIA)){
convertedPath = getRealPathFromURI(orgUri);
} else if(orgUri.toString().contains(AUDIOMEDIA)){
convertedPath = getRealAudioPathFromURI(orgUri);
}
else if(orgUri.toString().contains(VIDEOMEDIA)){
convertedPath = getRealvideoPathFromURI(orgUri);
}else {
if(orgUri.toString().contains("content")){
convertedPath = getFilePathFromContentUri(orgUri,
getApplicationContext().getContentResolver());
} else {
convertedPath = orgUri.getPath();
}
}
try this one
Uri selectedFile = data.getData();
String path = selectedFile.getPath();
it works for me.
if it is not than let me inform i have another way too
This works for me...
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >=
Build.VERSION_CODES.KITKAT;
Log.i("URI",uri+"");
String result = uri+"";
// DocumentProvider
// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isKitKat && (result.contains("media.documents"))) {
String[] ary = result.split("/");
int length = ary.length;
String imgary = ary[length-1];
final String[] dat = imgary.split("%3A");
final String docId = dat[1];
final String type = dat[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
} else if ("audio".equals(type)) {
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
dat[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
else
if ("content".equalsIgnoreCase(uri.getScheme())) {
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 column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
It is a problem of decode. So the Solution is to add decode to the method. as given below:
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) throws UnsupportedEncodingException {
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
String result = java.net.URLDecoder.decode(filePath, "UTF-8");
return result;
}
my onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
//image.setImageBitmap(null);
//Uri return from external activity
orgUri = data.getData();
text1.setText("fichier à envoyer " + orgUri.toString() + "\n");
// imagepath = orgUri.toString() ;
//path converted from Uri
//convertedPath = orgUri.getPath();
if(orgUri.toString().contains(IMAGEMEDIA)){
convertedPath = getRealPathFromURI(orgUri);
} else if(orgUri.toString().contains(AUDIOMEDIA)){
convertedPath = getRealAudioPathFromURI(orgUri);
}
else if(orgUri.toString().contains(VIDEOMEDIA)){
convertedPath = getRealvideoPathFromURI(orgUri);
}else {
if(orgUri.toString().contains("content")){
try {
convertedPath = getFilePathFromContentUri(orgUri,
getApplicationContext().getContentResolver());
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
convertedPath = orgUri.getPath();
}
}
// text2.setText("Real Path: " + convertedPath + "\n");
imagepath = convertedPath;
uriFromPath = Uri.fromFile(new File(convertedPath));
}
}

Categories

Resources