how get actual file path from file chooser using intent - android

how to get file path using intent. I am using this code to choose the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
// intent.setData(uri);
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),PICKFILE_RESULT_CODE);
} catch (android.content.ActivityNotFoundException ex)
{// Potentially direct the user to the Market with a Dialog
Toast.makeText(getApplicationContext(), "Please install a File Manager.", Toast.LENGTH_LONG).show();
}
now i want to get actual file path in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICKFILE_RESULT_CODE && resultCode == RESULT_OK
&& data != null) {
Uri selectedFile = data.getData();
String[] filePathColum = { };
Cursor cursor = getContentResolver().query(selectedFile,
filePathColum, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColum[0]);
String FilePath = cursor.getString(columnIndex);
but when i try to get file path it crashed
how i get file path

Related

Path of selected image is null

I am trying to get the real path of a URI.
First I start the gallery app through an intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), SELECT_IMAGE );
After that the onActivityResult gets called, where I try to get the absolut path of the URI.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK) {
Uri uri;
if (requestCode == SELECT_IMAGE) {
final Uri uri_data = data.getData();
// Get the path from the Uri
final String path = getPathFromURI(uri_data);
if (path != null) {
File f = new File(path);
uri = Uri.fromFile(f);
}
}
}
} catch (Exception e) {
Log.e("FileSelectorActivity", "File select error", e);
}
}
The uri_data contains "content://com.android.providers.media.documents/document/image%3A67", but the resulting path is null.
The pathFromUri method looks like this:
private String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Here the column_index is 0, but cursor.getString returns null.
Why does this happen?
I have the permission android.permission.READ_EXTERNAL_STORAGE
EDIT:
So I want to take a picture through the camera app, and the user then chooses the image. So the file should be acutally stored on the phone (which is, since I am testing it on my phone)
EDIT:
Okey, the solution was to request the permissions at runtime...sorry guys

how to get a real path of PDF file in android

we want to choose a pdf file using intent from a gallery so how can get a real path of a pdf file. We want to choose a PDF file from a gallery and upload this file on a server.
public String getPathFromURI(Context context, Uri contentUri) {
if ( contentUri.toString().indexOf("file:///") > -1 ){
return contentUri.getPath();
}
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
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);
}finally {
if (cursor != null) {
cursor.close();
}
}
}
Hi here is sample code for selecting pdf file from external storage and get file's path using which you can access file's data and upload data on your server.
Here PICK_IMAGE is any number you want as your request code.
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),PICK_IMAGE);
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
try {
Uri uri1 = data.getData();
String path = String.valueOf(uri1);
String path_lastPart = path.substring(path.indexOf("/storage"));
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// Do the file write
path_lastPart = path_lastPart.replace("%20", " ");
File yourFile = new File(path_lastPart);
} else {
// Request permission from the user
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
} catch (Exception e2) {
Log.e("macro", "" + e2);
}
}
}

Pick any file using intent in android

I'm using following method to call pick any file but it doesn't work properly.
private void fileIntent(int file)
{
if ((ActivityCompat.checkSelfPermission(ICShowFileCabinetDetails.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, file);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), file);
}
}
Following permissions are set in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
OnActivtyresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == SELECT_FILE && data != null) {
try {
mProPic = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
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);
// String filename = selectedImage.getLastPathSegment();
String[] filenames = picturePath.split("\\/");
int count = filenames.length;
String name = filenames[count - 1];
imagepickerselected = 1;
UploadIamgeinServer(1, name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Choose file getting open whenever i click to choose file in button click. But all files are shown like hidden except images, Click doest work. Without method in it button click works fine. If anyone found errors in code please let me know.
Thanks
try this code this my code only for .xls use yours.
or add read and write permission in manifest file
oncreate declare permission
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}
}
onclick of you button write this code
path= String.valueOf(Environment.getExternalStorageDirectory());
File file = new File(path);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.ms-excel");
try {
startActivityForResult(pdfOpenintent.createChooser(intent, "Select file"), 0); }
catch (ActivityNotFoundException e) {
}
onactivityresult yud get file path
public void onActivityResult(int requestCode, int resultCode, Intent result){
if (resultCode == RESULT_OK){
if (requestCode == 0) {
Uri data = result.getData();
else{
// CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");
Toast.makeText(Import_act.this,"Wrong File Selected ", Toast.LENGTH_SHORT).show();
}
}
}
}
I think you should add like this intent.addCategory(Intent.CATEGORY_OPENABLE);
. For more visit this link, Select File from file manager via Intent. I hope this may help you.

Select bitmap image from gallary and on button click save to Sdcard

hello very good noon to all.Actually i want to select an image from gallery and then i want to save the selected image in Sdcard which is available in android device.
pick image from Sd card:
Intent mediaChooser = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
// comma-separated MIME types
mediaChooser.setType("image/*");
startActivityForResult(mediaChooser, RESULT_LOAD_WATER_IMAGE);
And On Activity Result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
String path;
path = getRealPathFromURI(data.getData());
}
break;
}
Implementation Of getRealPathFromURI:
public String getRealPathFromURI(Uri contentUri) {
try {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e) {
return contentUri.getPath();
}
}
Save Image To Sd Card On Click:
// TODO Auto-generated method stub
String root = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(root + "/Your Folder Name");
myDir.mkdirs();
String fname = "Your File Name";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("error" + e);
}
Using the code below, you can pick up an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
After that, the picked up image will be return by the onActivityResult() method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK && requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
//Get the image file path
final String imageFilePath = cursor.getString(0);
cursor.close();
//save it the sdcard
saveToSDCard(imageFilePath);
}
super.onActivityResult(requestCode, resultCode, data);
}

Picking up an audio file android

I need to fetch an audio file from SD Card and play it. I think this can be done by getting URI of an audio file. So, to pick an audio file I'm using following code:
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), reqCode);
Now, I can browse for audio files and select one of them.
QUESTION: How to read the URI of picked file in my onActivityResult?
You can put below codes in your project when you want to select audio.
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload,1);
And override onActivityResult in the same Activity, as below
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == 1){
if(resultCode == RESULT_OK){
//the selected audio.
Uri uri = data.getData();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
first of all open gallery through intent -
public void openGalleryForAudio() {
Intent videoIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(videoIntent, "Select Audio"), AUDIO_REQUEST);
}
Then onActivityResult you should catch data -
if (requestCode == AUDIO_REQUEST && null != data) {
if (requestCode == AUDIO_REQUEST) {
Uri uri = data.getData();
try {
String uriString = uri.toString();
File myFile = new File(uriString);
// String path = myFile.getAbsolutePath();
String displayName = null;
String path2 = getAudioPath(uri);
File f = new File(path2);
long fileSizeInBytes = f.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;
if (fileSizeInMB > 8) {
customAlterDialog("Can't Upload ", "sorry file size is large");
} else {
profilePicUrl = path2;
isPicSelect = true;
}
} catch (Exception e) {
//handle exception
Toast.makeText(GroupDetailsActivity.this, "Unable to process,try again", Toast.LENGTH_SHORT).show();
}
// String path1 = uri.getPath();
}
}
This function is use for absolute path of audio file
private String getAudioPath(Uri uri) {
String[] data = {MediaStore.Audio.Media.DATA};
CursorLoader loader = new CursorLoader(getApplicationContext(), uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
No need to add type here like audio/*. It will crash to search such type of action.
Try this. It worked for me.
val intent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, AUDIO_REQUEST_CODE)
final Uri uri=Uri.parse(Environment.getExternalStorageDirectory()+"/Audio/abc.mp3");
Replace /Audio/abc.mp3 with your path of mp3 file on sdcard.
Dont forget to check if the external storage is mounted.
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
//To pick audio file from device. Place below code in calling activity
int REQUEST_CODE = 1001;
Intent audioIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(audioIntent,REQUEST_CODE);
// Override onActivityForResult method in activity
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK ){
//the selected audio.Do some thing with uri
Uri uri = data.getData();
}
super.onActivityResult(requestCode, resultCode, data);
}

Categories

Resources