0% found this document useful (0 votes)
108 views14 pages

Android File Chooser Implementation

The document discusses using an Intent to allow users to select files from their device to return to an Android app. It provides code to launch a file selection intent that works for most devices but not Samsung devices. An improved solution is presented that uses a Samsung-specific intent action along with the standard intent, so it works for both Samsung and other devices. When complete, it returns the URI path of the selected file.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views14 pages

Android File Chooser Implementation

The document discusses using an Intent to allow users to select files from their device to return to an Android app. It provides code to launch a file selection intent that works for most devices but not Samsung devices. An improved solution is presented that uses a Samsung-specific intent action along with the standard intent, so it works for both Samsung and other devices. When complete, it returns the URI path of the selected file.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

android asyncTask dialog Circle

new Load().execute(); to call.


class Load extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
[Link]();
ProgressDialog progDailog = new ProgressDialog([Link]);
[Link]("Loading...");
[Link](false);
[Link](ProgressDialog.STYLE_SPINNER);
[Link](true);
[Link]();
}
@Override
protected String doInBackground(String... aurl) {
//do something while spinning circling show
return null;
}
@Override
protected void onPostExecute(String unused) {
[Link](unused);
[Link]();
}
}
shareimprove this answer
edited Mar 13 '14 at 12:28
Community♦
11
answered Feb 7 '12 at 3:03
brian
3,3912573115
• Thanks Brian and everyone... This is very helpful. I got it all together.. – james winters Feb 8 '12 at 4:59
• 2
Then please make a tick left. – brian Feb 8 '12 at 5:44
• About ProgressDialog([Link]); in the class Load gives an error. Of course. What must we use? – Boris
Karloff Dec 31 '13 at 20:14
• 1
@Boris Karloff you have to use the name of the Activity where your Asynctask resides in. If this private class
"Load" - which extends from AsyncTask - is inside the class "MainActivity" then you have to use
"ProgressDialog([Link])" instead. – DuKes0mE Mar 18 '14 at 9:57
add a comment

11
private class LoadAssync extends AsyncTask<String, Void, Void> {

protected void onPreExecute() {

ProgressDialog dialog;
[Link]("Loading...");
[Link]();
}

protected Void doInBackground(final String... args) {


// you can do the code here
return null;

protected void onPostExecute(final Void unused) {

if ([Link]()) {
[Link]();
}

}
}
u can call assync like this
LoadAssync mAsyync=new LoadAssync();
[Link](null);

You can try following code,


progDailog = [Link](loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your code goes here
}
}).start();

Handler progressHandler = new Handler()


{
public void handleMessage(Message msg1)
{
[Link]();
}
}
Pick any kind file via an Intent on Android
Ask Question

79
28
I would like to start an intentchooser for apps which can return any kind of file
Currently I use (which I copied from the Android email source code for file
attachment)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
[Link](Intent.CATEGORY_OPENABLE);
[Link]("*/*");
Intent i = [Link](intent, "File");
startActivityForResult(i, CHOOSE_FILE_REQUESTCODE);
But it only shows "Gallery" and "Music player" on my Galaxy S2. There is a file
explorer on this device and I would like it to appear in the list. I would also like the
camera app to show in the list, so that the user can shoot a picture and send it
through my app. If I install Astro file manager it will respond to that intent, too. My
customers are Galaxy SII owners only and I don't want to force them to install Astro
file manager given that they already have a basic but sufficient file manager.
Any idea of how I could achieve this ? I am pretty sure that I already saw the default
file manager appear in such a menu to pick a file, but I can't remember in which app.
android file android-intent intentfilter
shareimprove this question
edited Jan 16 '17 at 22:17
Willi Mentzel
10k114770
asked Jan 20 '12 at 17:38
ErGo_404
66421121
• You will need very different code to shoot a picture then to choose a file. I don't actually think most file explorers
can return a file, but I might be wrong. – dtech Jan 20 '12 at 18:00
• can u specify what kind of files you need to be accessed primarily? – subrussn90 Jan 20 '12 at 18:02
• 1
@dtech : I dont expect the file explorer to return the file, I only need it's path. – ErGo_404 Jan 23 '12 at 8:13
• @subrussn90 : I need to let the user pick any kind of file. It could be pdfs, .doc, .zip, ANY kind of
file. – ErGo_404 Jan 23 '12 at 8:14
• is it enough that you get the Uri of the specified file on the sd card??? – subrussn90 Jan 23 '12 at 18:49
show 1 more comment

5 Answers
active oldest votes

70
Not for camera but for other files..
In my device I have ES File Explorer installed and This simply thing works in my
case..
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
[Link]("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
shareimprove this answer
edited Aug 3 '15 at 15:42
answered Jan 20 '12 at 18:21
user370305
90.9k21146143
• 3
It does work with an external file explorer (such as ES File Explorer or Astro File Manager, but not with the
Samsung file explorer. It seems odd that they did not implement the correct intent filters to respond to that
action. – ErGo_404 Jan 23 '12 at 8:12
• is there some solution that works on Samsung ? – Lukap Sep 27 '12 at 8:24
• 2
how can I get the selected file ? I guess it's the path, but how ? – Francisco Corrales Morales Nov 26 '14 at
17:31
• 1
@FranciscoCorralesMorales - in onActivityResult()- You can get Uri of the File. – user370305 Nov 26
'14 at 17:38
• 1
PICKFILE_RESULT_CODE should be PICKFILE_REQUEST_CODE. – Áron Lőrincz Aug 3 '15 at 15:27
show 5 more comments

Object 2

43
Samsung file explorer needs not only custom action
([Link].PICK_DATA), but also category part
(Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.
Intent intent = new Intent("[Link].PICK_DATA");
[Link]("CONTENT_TYPE", "*/*");
[Link](Intent.CATEGORY_DEFAULT);
You can also use this action for opening multiple files:
[Link].PICK_DATA_MULTIPLE Anyway here is my solution which
works on Samsung and other devices:
public void openFile(String mimeType) {

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);


[Link](mimeType);
[Link](Intent.CATEGORY_OPENABLE);

// special intent for Samsung file manager


Intent sIntent = new Intent("[Link].PICK_DATA");
// if you want any file type, you can skip next line
[Link]("CONTENT_TYPE", mimeType);
[Link](Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with Samsung file manager
chooserIntent = [Link](sIntent, "Open file");
[Link](Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
} else {
chooserIntent = [Link](intent, "Open file");
}

try {
startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
} catch ([Link] ex) {
[Link](getApplicationContext(), "No suitable File Manager was found.",
Toast.LENGTH_SHORT).show();
}
}
This solution works well for me, and maybe will be useful for someone else.
shareimprove this answer
edited Jan 23 at 12:41
flipm0de
123110
answered Jul 30 '13 at 14:30
Chupik
826710
• It almost works for me, except the fact that sIntent, when launched, accepts no file of any type. I can browse
through folders, but that's it. – Radu Nov 8 '13 at 11:24
• 1
This only works for Samsung devices. – uiltonsantos Oct 12 '15 at 15:09
• 1
What about the other 11k of Android devices. – Oliver Dixon May 21 '16 at 12:15
• 1
How set URI for this intent can you please help me ? – PriyankaChauhan Jul 27 '17 at 6:03
• 1
In case of Samsung Intent ("[Link].PICK_DATA") you can try to put String extra
"FOLDERPATH" or "START_FOLDER" – Chupik Mar 27 '18 at 8:26
show 8 more comments
32
this work for me on galaxy note its show contacts, file managers installed on device,
gallery, music player
private void openFile(Int CODE) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
[Link]("*/*");
startActivityForResult(intent, CODE);
}
here get path in onActivityResult of activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String Fpath = [Link]();
// do somthing...
[Link](requestCode, resultCode, data);

}
shareimprove this answer
answered Jun 25 '12 at 0:16
alireza
32132
• 6
How to convert getting uri into [Link] ? – Anand Savjani Aug 12 '15 at 13:36
• Not sure about getting [Link], but can be opened
with: [Link]/reference/android/content/…How to get simple name is
here: [Link]/a/23270545/755313 – demaksee Sep 18 '15 at 16:53
• 3
how to pick a folder? – hornet2319 Oct 26 '15 at 14:29
add a comment
1
Turns out the Samsung file explorer uses a custom action. This is why I could see the
Samsung file explorer when looking for a file from the samsung apps, but not from
mine.
The action is "[Link].PICK_DATA"
I created a custom Activity Picker which displays activities filtering both intents.
shareimprove this answer
answered Jan 23 '12 at 10:41
ErGo_404
66421121
• Hi, can you explain this a bit more? For samsung galaxy phones I use Intent selectFile = new
Intent( "[Link].PICK_DATA"); but it causes an error – MScott Apr 30 '12 at 0:41
• 2
@mole363 Which error do you get ? – ErGo_404 May 29 '12 at 9:22
• I'm not sure right now, but I can check it later. I think it's the Activity Not Found exception. Do you have any
working solution? I almost tried everything and didn't manage to fix it – MScott May 29 '12 at 20:21
• This intent has worked for me on the Galaxy SII. Tried it on a GT-B5510 (Galaxy Y Pro) and it didn't work. I
think it is just not reliable if you want to target all Samsung devices. I ended up integrating an open source file
manager into my application, but it is a heavy solution for such a basic need. – ErGo_404 Jun 4 '12 at 7:38
• How set URI for this intent can you please help me ? – PriyankaChauhan Jul 27 '17 at 6:04
add a comment
-1
If you want to know this, it exists an open source library called aFileDialog that it is
an small and easy to use which provides a file picker.
The difference with another file chooser's libraries for Android is that aFileDialog
gives you the option to open the file chooser as a Dialog and as an Activity.
It also lets you to select folders, create files, filter files using regular expressions and
show confirmation dialogs.
shareimprove this answer
android-file-chooser

there is a way to taste the master branch with [Link]:


[Link] the jitpack repository url to your root [Link]:

allprojects {
repositories {
google()
jcenter()
maven { url "[Link] }
}
}
[Link] android-file-chooser
implementation '[Link]:android-file-chooser:master-SNAPSHOT'
// implementation '[Link]:android-file-chooser:v1.1.10'

Codes
FileChooser android library give a simple file/folder chooser in single call:

Choose a Folder

new ChooserDialog().with(this)
.withFilter(true, false)
.withStartFile(startingDir)
// to handle the result(s)
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link]([Link], "FOLDER: " + path,
Toast.LENGTH_SHORT).show();
}
})
.build()
.show();
Choose a File

new ChooserDialog().with(this)
.withStartFile(path)
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link]([Link], "FILE: " + path,
Toast.LENGTH_SHORT).show();
}
})
// to handle the back key pressed or clicked outside the dialog:
.withOnCancelListener(new [Link]() {
public void onCancel(DialogInterface dialog) {
Log.d("CANCEL", "CANCEL");
[Link](); // MUST have
}
})
.build()
.show();

Wild-match

new ChooserDialog().with(this)
.withFilter(false, false, "jpg", "jpeg", "png")
.withStartFile(path)
.withResources([Link].title_choose_file, [Link].title_choose,
[Link].dialog_cancel)
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link]([Link], "FILE: " + path,
Toast.LENGTH_SHORT).show();
}
})
.build()
.show();

Regex filter

new ChooserDialog().with(this)
.withFilterRegex(false, false, ".*\\.(jpe?g|png)")
.withStartFile(path)
.withResources([Link].title_choose_file, [Link].title_choose,
[Link].dialog_cancel)
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link]([Link], "FILE: " + path,
Toast.LENGTH_SHORT).show();
}
})
.build()
.show();

Date Format String

Since 1.1.3, new builder options withDateFormat(String) added.


new ChooserDialog().with(this)
.withFilter(true, false)
.withStartFile(startingDir)
.withDateFormat("HH:mm") // see also SimpleDateFormat format specifiers
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link]([Link], "FOLDER: " + path,
Toast.LENGTH_SHORT).show();
}
})
.build()
.show();

Modify Icon or View Layout of AlertDialog:


Since 1.1.6, 2 new options are available:

new ChooserDialog().with(this)
.withFilter(true, false)
.withStartFile(startingDir)
.withIcon([Link].ic_file_chooser)
.withLayoutView([Link].alert_file_chooser)
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link]([Link], "FOLDER: " + path,
Toast.LENGTH_SHORT).show();
}
})
.build()
.show();

Customizable NegativeButton

1.1.7 or Higher, try withNegativeButton() and withNegativeButtonListener() instead


of withOnBackPressedListener().

withOnBackPressedListener

deprecated.

onCancelListener

will be triggered on back pressed or clicked outside of dialog.


onCancelListener
You MUST invoke [Link]() while override the default onCancelListener :
.withOnCancelListener(new [Link]() {
public void onCancel(DialogInterface dialog) {
Log.d("CANCEL", "CANCEL");
[Link](); // MUST have
}
})

New calling chain

1.1.7+, new constructor ChooserDialog(context) can simplify the chain invoking,


such as:
new ChooserDialog(this)
.withFilter(true, false)
.withStartFile(startingDir)
...

And, old style is still available. No need to modify your existing codes.

withRowLayoutView(resId)
1.1.8+. Now you can customize each row.

withFileIcons
1.1.9+. withFileIcons(resolveMime, fileIcon, folderIcon) and withFileIconsRes(resolveMime,
fileIconResId, folderIconResId) allow user-defined file/folder icon.
resolveMime: true means that DirAdapter will try get icon from the associated app
with the file's mime type.
new ChooserDialog(ctx)
.withStartFile(_path)
.withResources([Link].title_choose_any_file, [Link].title_choose,
[Link].dialog_cancel)
.withFileIconsRes(false, [Link].ic_my_file, [Link].ic_my_folder)
.withChosenListener(new [Link]() {
@Override
public void onChoosePath(String path, File pathFile) {
[Link](ctx, "FILE: " + path, Toast.LENGTH_SHORT).show();
}
})
.build()
.show();
withAdapterSetter(setter)
1.1.9+. a AdapterSetter can be use to customize the DirAdapter.
.withAdapterSetter(new [Link]() {
@Override
public void apply(DirAdapter adapter) {
[Link](fileIcon);
[Link](folderIcon);
[Link](tryResolveFileTypeAndIcon);
}
})
withNavigateUpTo(CanNavigateUp)
1.1.10+. withNavigateUpTo
.withNavigateUpTo(new [Link]() {
@Override
public boolean canUpTo(File dir) {
return true;
}
})
withNavigateTo(CanNavigateTo)
1.1.10+. withNavigateTo
.withNavigateTo(new [Link]() {
@Override
public boolean canNavigate(File dir) {
return true;
}
})
enableOptions(true)
a tri-dot menu icon will be shown at bottom left corner. this icon button allows
end user to create new folder on the fly or delete one.
further tunes:

•withOptionResources(@StringRes int createDirRes, @StringRes int deleteRes, @StringRes


int newFolderCancelRes, @StringRes int newFolderOkRes)
•withOptionIcons(@DrawableRes int optionsIconRes, @DrawableRes int createDirIconRes,
@DrawableRes int deleteRes)
•withNewFolderFilter(NewFolderFilter filter)
•withOnBackPressedListener(OnBackPressedListener listener)
•withOnLastBackPressedListener(OnBackPressedListener listener)
see the sample codes in demo app.

NOTE:

[Link] WRITE_EXTERNAL_STORAGE permission should be declared in


your [Link].
[Link]'ll ask the extra runtime permission to WRITE_EXTERNAL_STORAGE on
Android M and higher too.
disableTitle(true)
as named as working.

psuedo .. SDCard Storage and .. Primary Storage

Under Kotlin
class MyFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,


savedInstanceState: Bundle?): View? {
val root = [Link]([Link].fragment_book, container, false)
root.upload_button.setOnClickListener { _: View ->
ChooserDialog().with(activity)
.withStartFile([Link]().absolutePath)
// .withStartFile([Link]()+"/")
.withFilterRegex(false, false, ".*\\.(jpe?g|png)")
.withChosenListener { path, pathFile -> activity!!.toast("FILE: $path /
$pathFile") }
.build()
.show()
}

return root
}
}
And:
ChooserDialog(context)
.withFilterRegex(false, true, ".*\\.(jpe?g|png)")
.withStartFile(startPath)
.withResources([Link].title_choose_file, [Link].title_choose,
[Link].dialog_cancel)
.withChosenListener { path, pathFile ->
[Link](context, "FILE: $path; PATHFILE: $pathFile",
Toast.LENGTH_SHORT).show()

//_path = path
//_tv.setText(_path)
////_iv.setImageURI([Link](pathFile));
//_iv.setImageBitmap([Link](pathFile))
}
.withNavigateUpTo { true }
.withNavigateTo { true }
.build()
.show()
References
1. [Link]
2. [Link]
3. [Link]

Common questions

Powered by AI

To integrate an external file manager into an Android application for picking files, consider embedding an open-source library that acts as a file chooser, such as aFileDialog. This library allows you to open a file chooser dialog or activity and provides extensive customization options, like selecting folders, creating files, filtering by regex, and confirming actions . Ensure your app has the proper permissions and uses the library's API to incorporate it seamlessly into your app's workflow .

An Android application can allow users to pick any kind of file using an Intent by creating an Intent with the action Intent.ACTION_GET_CONTENT. Set the type of the Intent to '*/*' to allow all file types, and add the CATEGORY_OPENABLE category to filter for files that can be opened . If targeting Samsung devices, you can use a custom action like 'com.sec.android.app.myfiles.PICK_DATA' and include the CONTENT_TYPE extra and CATEGORY_DEFAULT category .

Ensuring compatibility for file picking across different Android devices and versions requires using intents that cover a wide range of file managers by using ACTION_GET_CONTENT with wildcard MIME types and categories like CATEGORY_OPENABLE. For device-specific solutions, such as Samsung's file manager, use intents like 'com.sec.android.app.myfiles.PICK_DATA' with necessary extras and category adjustments. Additionally, handle compatibility with user-installed file managers by providing intent filters and fallbacks to ensure an application can still access files even if some options fail .

The ChooserDialog library benefits Android applications by providing a user-friendly interface for selecting files or folders, supporting filtering options, regular expressions, and easy integration as a dialog or activity . Developers can handle file selection when the back button is pressed by implementing the withOnCancelListener method, ensuring dialog.cancel() is called to gracefully dismiss the dialog and handle any necessary cleanup operations .

To display a ProgressDialog while performing a task in the background using AsyncTask in Android, follow these steps: First, in the onPreExecute() method, initialize and show a ProgressDialog to indicate loading. In the doInBackground() method, perform the background task. Finally, in the onPostExecute() method, dismiss the ProgressDialog to hide it once the task is complete .

To display a ProgressDialog that updates based on task status in an AsyncTask, first initialize and show the dialog in onPreExecute. During doInBackground, use publishProgress() to send progress updates, which are received in the onProgressUpdate method. In onProgressUpdate, update the ProgressDialog's message or progress to reflect the current task status. Finally, dismiss the ProgressDialog in onPostExecute once the task completes .

To resolve ActivityNotFoundException when opening a file manager, check if there is an app available to handle the intent using PackageManager's resolveActivity method before proceeding with startActivityForResult. If no default file manager exists, you can provide a chooser with Intent.createChooser to select from available apps, or integrate a third-party file manager library like aFileDialog that directly handles file selections within your app .

Common issues when using Intents to choose a file on Samsung devices include the Samsung file explorer not appearing or responding to the typical ACTION_GET_CONTENT intent. This can be addressed by using a special intent with the action 'com.sec.android.app.myfiles.PICK_DATA', adding an extra for CONTENT_TYPE, and including CATEGORY_DEFAULT . Additionally, ensure that the device's package manager resolves the custom intent action to ensure compatibility with Samsung file managers .

To modify a ChooserDialog in Android to select specific file types and customize the UI, use the withFilterRegex method to filter files by their extensions, such as ".jpg" or ".png" . Customize the UI by using withIcon and withLayoutView to change icons and layout. You can further adjust user interactions using withNavigateUpTo or withNavigateTo, and customize dialog buttons with methods like withOnCancelListener to handle cancel events .

MIME types are crucial for Android Intents in file picking because they allow the application to specify the type of content it can manage with the intent. By setting the MIME type to '*/*', applications can signal that any file type can be selected. Alternatively, specifying a particular MIME type filters the results to only show compatible files. They ensure the compatible file manager or app will respond to the intent properly .

You might also like