How to Select File on android using Intent - android

I use this code to use Intent to select any type of file and get it's path in my application
//this when button click
public void onBrowse(View view) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("file/*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
String path = "";
if(requestCode == ACTIVITY_CHOOSE_FILE)
{
Uri uri = data.getData();
String FilePath = getRealPathFromURI(uri); // should the path be here in this string
System.out.print("Path = " + FilePath);
}
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
the problem when the file browser open i can't select a file it seems like it's not enable when i pressed on a file nothing happend so what is the wrong with this code
i upload a screenshot from my android mobile
image
Thanks in advance

the type of a file is .txt
Then use text/plain as a MIME type. As Ian Lake noted in a comment, file/* is not a valid MIME type.
Beyond that, delete getRealPathFromURI() (which will not work). There is no path, beyond the Uri itself. You can read in the contents identified by this Uri by calling openInputStream() on a ContentResolver, and you can get a ContentResolver by calling getContentResolver() on your Activity.

Change the line :
chooseFile.setType("file/*");
to
chooseFile.setType("*/*");
This will help you choose any type of file.

Related

Pick image from gallery file path returns NULL

I want to pick an image from the gallery and get it's path. Here is the code I use to open the gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1111);
and onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Log.d("TAG", "onActivityResult: " + filePath);
}
}
filePath always is null if I select the image from the default system image picker, although it is working fine if select an image from the gallery app. What is wrong with my code ?
There is no requirement for ACTION_GET_CONTENT to return a Uri from the MediaStore or a Uri that otherwise has a DATA column.
Also note that you do not have access to the DATA column for MediaStore Uri values on Android 10 and above, so "working fine" is only true temporarily.
I want to pick an image from the gallery and get it's path
There is no path. The user could be choosing a piece of content from a cloud storage provider, such as Google Drive.
See also:
Getting the Absolute File Path from Content URI for searched images
Android - Get real path of a .txt file selected from the file explorer
onActivityResult's intent.getPath() doesn't give me the correct filename
private void loadGallery() {
Intent choose = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choose, PICK_IMAGE_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_GALLERY) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
}
}
}
MediaStore.Images.Media.DATA is deprecated from android 10. Though it will work, if you add the following to AndroidManifest.xml
android:requestLegacyExternalStorage="true"
But it is a temporary solution, if you want to read a file and do something with it you should store it to the app-specific temporary storage, that is there for every android application. Using the app-specific storage do not requires any permission from the user.
So you can use the below code, if you already have the Uri of selected file.
val parcelFileDescriptor =
contentResolver.openFileDescriptor(selectedImageUri!!, "r", null) ?: return
val inputStream = FileInputStream(parcelFileDescriptor.fileDescriptor)
val file = File(cacheDir, contentResolver.getFileName(selectedImageUri!!))
val outputStream = FileOutputStream(file)
inputStream.copyTo(outputStream)
And the function to get the file name from the Uri is
fun ContentResolver.getFileName(fileUri: Uri): String {
var name = ""
val returnCursor = this.query(fileUri, null, null, null, null)
if (returnCursor != null) {
val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
returnCursor.moveToFirst()
name = returnCursor.getString(nameIndex)
returnCursor.close()
}
return name
}
Source: Android Upload File to Server

How to get non-null data out of Intent on file selection?

I would like to let user select an audio file, and then I would like to get the file path of it. However I have even simpler problem, because Uri of the intent I get is null. How I could get something meaningful, i.e. non-null?
Starting intent:
private void MainActivity_Click1(object sender, System.EventArgs e)
{
//var intent = new Intent();
var intent = new Intent(Intent.ActionPick, Android.Provider.MediaStore.Audio.Media.ExternalContentUri);
intent.SetType("audio/*");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(
Intent.CreateChooser(intent, "Select audio file"), SelectAudioCode);
}
And responding to the selection:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok && requestCode==SelectAudioCode)
{
Android.Net.Uri uri = Intent.Data;
audioFileNameText.Text = uri == null ? "<NULL>" : uri.ToString();
}
}
No matter how I create the intent (see the code above), I see always NULL.
Update: if I use the Intent passed via parameter, the Data property of it is null as well.
I would like to let user select an audio file, and then I would like to get the file path of it. However I have even simpler problem, because Uri of the intent I get is null.
You can get the content Uri from data.Data. But if you want to get the file path out of content uri, you need to convert the content uri into real path:
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
string abc= getRealPathFromURI(this,data.Data);
}
public string getRealPathFromURI(Context context, Uri contentUri)
{
ICursor cursor = null;
try
{
string[] proj = { MediaStore.Audio.AudioColumns.Data};
cursor = ContentResolver.Query(contentUri, proj, null, null, null);
int column_index = cursor.GetColumnIndexOrThrow(MediaStore.Audio.AudioColumns.Data);
cursor.MoveToFirst();
return cursor.GetString(column_index);
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
}
Explaination Update:
The intent you are currently using by Intent.Data is the intent that start current activity, not the intent that chooser returned back:
So instead of using Intent.Data you need to use the intent returned by the chooser activity, which is data argument:
Looks like you are using Xamarin. The Java equivalent of what you are trying to achieve is this.
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType("audio/*");
this.startActivityForResult(intent,RESULT_CODE);

Video path is not accessing in android 4.4 when I am going to pic a video from gallery

Hello friends I am using the following code to pic a video from gallery..
private static final int SELECT_VIDEO = 3;
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select a video"), SELECT_VIDEO);
On activity result:
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data)
{
try{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO)
{
Uri selectedImageUri = data.getData();
videopath = getPath(selectedImageUri);
}
}
}catch(Exception e){
// MLog.e("On Activity result.", "Error: "+e);
}
}
//get path method
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE, MediaStore.Video.Media.DURATION};
Cursor cursor = managedQuery(uri, projection, null, null, null);
cursor.moveToFirst();
String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
int fileSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
long duration = TimeUnit.MILLISECONDS.toSeconds(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)));
return filePath;
}
Now using above code I am getting null for video path in android 4.4. Can any one help me and let me know what should I have to use that I can pic the video from gallery successfully in android 4.4.
Now using above code I am getting null for video path in android 4.4.
You will get null in many cases, but particularly on Android 4.4+. That is because there does not have to be a file that you can access that corresponds to the video. A Uri is not necessarily a File.
You need to get rid of getPath() and use the Uri properly. For example, MediaPlayer and VideoView can work with the Uri directly. If you need the bytes of the video, use openInputStream() on ContentProvider to read in the video.

Playing a file in android mediaplayer

I want to play a video file recorded to be played in the mediaplayer of android.I want to call the media player through the intent and want to play the corresponding file of the passed uri.When I was trying I am getting an exception ActivityNotFound can anyone help me with a code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_VIDEO_CAPTURED) {
uriVideo = data.getData();
Toast.makeText(VedioRecording.this, uriVideo.getPath(),
Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
uriVideo = null;
Toast.makeText(VedioRecording.this, "Cancelled!", Toast.LENGTH_LONG)
.show();
}
if (requestCode == 2) {
selectedImageUri = data.getData();
// OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
Intent intent1 = new Intent(android.provider.MediaStore.INTENT_ACTION_MUSIC_PLAYER).setData(selectedImageUri);
startActivityForResult(intent1, 3);
// videoviewPlay.setVideoURI(selectedImageUri);
// videoviewPlay.start();
}
if (requestCode == 3) {
}
}
private String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else {
return null;
}
}
}
this is my code i am geting activitynotfound exception
The most common scenario in which you get an ActivityNotFound exception is when you attempt to launch an Activity you have created without declaring it in the manifest.
Post your code that you use to launch the Activity to be sure. If you're trying to use an activity that should be provided by the framework externally from your application, you may just be setting up the Intent incorrectly
Update after code posted...
Your code seems to be using the intent action INTENT_ACTION_MUSIC_PLAYER and passing an image url as data (is it the path to an image or are your variables just misnamed?). You get an ActivityNotFoundException because the system doesn't have any intent receivers registered to handle that scenario. Also, if you look at the documentation for this constant, you'll see that they marked it deprecated at some point:
http://developer.android.com/reference/android/provider/MediaStore.html#INTENT_ACTION_MUSIC_PLAYER
I would normally use Intent.ACTION_VIEW and pass a mime type along with the data. Something like the following...
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(pathToVideoFile), "video/*");
startActivity(intent);
By passing the mime type of "video/*" to setDataAndType, you're being more specific with your request to the system.
If you want to query the system to find out if an Intent can be handled (meaning that the user's device running your code has an Activity registered that can handle the Intent), you can use the PackageManager.queryIntentActivities method:
queryIntentActivities
String extension = MimeTypeMap
.getFileExtensionFromUrl(selectedImagePath);
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(extension);
Intent mediaIntent = new Intent(Intent.ACTION_VIEW);
mediaIntent.setDataAndType(Uri.parse(selectedImagePath),
mimeType);
startActivity(mediaIntent);
this is the code that helped me

Android: No Application perform this action, why?

i want to browse all Audio files, but i am getting error like No application can perform this action.. this is my code for browse activity...
--> private static final int SELECT_MUSIC = 1;
String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById(R.id.browse)).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("music/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select File"), SELECT_MUSIC);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_MUSIC) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(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.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
and i have also added permission to menifest file:: READ_PHONE_STATE
what's problem? any idea?
Thanks..
It means that No Application perform that action. Why? because None of the installed Applications perform that action. It has nothing to do with permissions.
You are probably running this on an emulator, which does not include any directory browser application.
The setType method is working with MIME type values only.
If you really just need the handling of music files "audio/" should be ok (as mentioned before). To be more flexible, you should try to detect the MIME code of the file.
Here is a code snippit how this may look like:
FileNameMap fileNameMap = URLConnection.getFileNameMap();
type = fileNameMap.getContentTypeFor("file://" + file.getPath());
Or (pre Gingerbread)
if (!file.getName().contains("."))
return null;
String ext = (String) file.getName().subSequence(
file.getName().lastIndexOf(".") + 1,
file.getName().length());
MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
type = mimeMap.getMimeTypeFromExtension(ext);
I usually use the combination of both methods (use the pre Gingerbread version if the first approach fails).
You can use:
intent.setType("audio/*"); instead of intent.setType("music/*");
Then you can choose a track, not a playlist.
Could you find a way to choose a playlist?
I have the same problem, looking for a way to open and choose a playlist.

Categories

Resources