Android studio choose file

Создание удобного OpenFileDialog для Android

Наверное, как и многие разработчики под Android, столкнулся на днях с необходимостью реализовать в своем приложении выбор файла пользователем. Так как изначально в Android такого функционала нет, обратился к великому и ужасному. Это показалось мне странным, но из вороха вопросов на stackoverflow и небольшого числа отечественных форумов можно выделить всего три основных источника:

  1. Android File Dialog – почти все ссылки из stackoverflow ведут сюда. В принципе, неплохое решение, но реализовано через отдельную activity, а хотелось чего-то в духе OpenFileDialog’а из .Net.
  2. В данной статье речь идет вообще об отдельном файл-менеджере, и почерпнуть какие-то идеи из неё не удалось.
  3. Идея же отсюда очень понравилась, однако, как мне показалось реализовать все это можно несколько красивее.

В результате, начав реализовывать своё решение, я столкнулся с некоторыми трудностями решать которые показалось очень интересно. А посему, решил описать в данной статье не просто готовое решение, а все шаги, которые к нему привели. Желающие пройти их вместе –
Итак, приступим! В любой привычной среде (я использую IntelliJ IDEA) создадим новое приложение. На главной activity расположим одну единственную кнопку и напишем к ней, пока пустой, обработчик нажатия:

Создадим новый класс с конструктором:

а в обработчике кнопки вызовем диалог:

Кнопки показались, теперь надо бы и сами файлы найти. Начнем поиск с корня sdcard, для чего определим поле:

и реализуем следующий метод:

(так как главное требование к классу – работать сразу у любого разработчика, без подключения дополнительных библиотек, — то никаких google-collections использовать не будем, и с массивами приходится работать по старинке), а в конструкторе к вызову setNegativeButton добавим .setItems(getFiles(currentPath), null).

Что же, неплохо, однако файлы не отсортированы. Реализуем для этого дела Adapter как внутренний класс, заменим setItems на setAdapter и немного перепишем getFiles:

Еще лучше, но нам надо по клику на папке идти внутрь. Можно достучаться до встроенного listview, но я просто подменил его собственным (это потом пригодится). Плюс, изменения adapter’а внутри обработчика listview вызывало exception, и список файлов пришлось вынести в отдельное поле:

Отлично, вот только нажав на папку Android мы получаем список всего из одного каталога data, и наше окно тут же уменьшается в размере.

Возможно это нормально, но мне это не понравилось, и я стал искать возможности размер сохранить. Единственный найденный мною вариант – это установка setMinimumHeight. Установка этого свойства для listview вызвала дополнительные проблемы, но они решились оберткой его в LinearLayout:

Результат, все равно получился немного не таким, каким хотелось бы: при старте диалог развернут на весь экран, а после перехода в каталог Android – уменьшается до 750px. Да еще и экраны разных устройств имеют разную высоту. Решим сразу обе этих проблемы, установив setMinimumHeight в максимально возможную для текущего экрана:

Не нужно пугаться того, что мы устанавливаем в setMinimumHeight полный размер экрана, сама система уменьшит значение до максимально допустимого.
Теперь появляется проблема понимания пользователя, в каком каталоге он сейчас находится, и возврата вверх. Давайте разберемся с первой. Вроде все легко — установить значение title в currentPath и менять его при изменении последнего. Добавим в конструктор и в метод RebuildFiles вызов setTitle(currentPath).

А нет – заголовок не изменился. Почему не срабатывает setTitle после показа диалога, документация молчит. Однако мы может это исправить, создав свой заголовок и подменив им стандартный:

И снова не все ладно: если пройти достаточно далеко, то строка в заголовок влезать не будет

Решение с установкой setMaximumWidth не верно, так как пользователь будет видеть только начало длинного пути. Не знаю, насколько верно мое решение, но я сделал так:

Решим теперь проблему с возвратом. Это достаточно легко, учитывая, что у нас есть LinearLayout. Добавим в него еще один TextView и немного отрефракторим код:

Возможность возвращаться на шаг вверх, может привести пользователя в каталоги, к которым ему доступ запрещен, поэтому изменим функцию RebuildFiles:

(cообщение пока не очень информативное, но вскоре мы добавим разработчику возможность исправить это).
Ни один OpenFileDialog не обходится без фильтра. Добавим и его:

Обратите внимание — фильтр принимает регулярное выражение. Казалось бы – все хорошо, но первая выборка файлов сработает в конструкторе, до присвоения фильтра. Перенесем её в переопределенный метод show:

Осталось совсем чуть-чуть: вернуть выбранный файл. Опять же, я так и не понял зачем нужно устанавливать CHOICE_MODE_SINGLE, а потом все равно писать лишний код для подсветки выбранного элемента, когда он (код) и так будет работать без CHOICE_MODE_SINGLE, а потому обойдемся без него:

Источник

Android studio choose file

android-file-library is a lightweight file/folder chooser.

1. with AndroidX

MediaStore for Android Q (still in beta)

A demo-app can be installed from Play Store.

A Xamarin nuget package by @Guiorgy can be found at

  • bugs fixed
  • minor fixes for themes
  • #60, #61, #62 fixed
  • revamped Dpad controls
  • added cancelOnTouchOutside and enableDpad (true by default)
  • mainly by Guiorgy.
Читайте также:  Где у андроида настройка usb

rewrite demo app

#48: add displayPath(boolean) , thank you @Guiorgy, and your android-smbfile-chooser.

new style demo app by @Guiorgy.

NOTE: displayPath is true by default now.

since v1.1.16, bumped targer sdk to 1.8 (please include the following into your build.gradle)

no WRITE_EXTERNAL_STORAGE requests if not enableOptions(true) ;

after requested permissions, try showing dialog again instead of return directly;

#42: onBackPressedListener not fired. Now, use withCancelListener to handle back key. see also below

#45: add titleFollowsDir(boolean) to allow title following the change of current directory.

create new folder on the fly, and the optional multiple select mode for developer, thx @Guiorgy.

Up ( .. ) on the primary storage root will be replaced with .. SDCard , it allows to jump to external storage such as a SDCard and going back available too.

DPad supports, arrow keys supports (#30)

More images (beyond v1.1.16) have been found at Gallery

android-file-chooser was released at jcenter, declare deps with:

for the newest version(s), looking up the badges above.

taste the fresh

there is a way to taste the master branch with jitpack.io:

  1. add the jitpack repository url to your root build.gradle:

Tips for using JitPack.io

To disable gradle local cache in your project, add stretegy into your top build.grable :

Sometimes it’s right, sometimes . no more warrants.

  1. I am hands down AlertDialog .
  2. Any codes about ChooserDialog , such as the following demo codes, should be only put into UI thread.

FileChooser android library give a simple file/folder chooser in single call (Fluent):

Choose a Folder

Date Format String

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

Modify Icon or View Layout of AlertDialog :

Since 1.1.6, 2 new options are available:

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

BackPressedListener will be called every time back key is pressed, and current directory is not the root of Primary/SdCard storage. LastBackPressedListener will be called if back key is pressed, and current directory is the root of Primary/SdCard storage.

OnCancelListener will be called when touching outside the dialog ( cancelOnTouchOutside must be set true), and when pressing back key. If BackPressedListener is overridden, it wont be called if dialog.dismiss is used instead of dialog.cancel . OnCancelListener will NOT be called when pressing the negative button. use withNegativeButtonListener for that.

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

1.1.8+. Now you can customize each row.

since 1.1.17, DirAdatper.GetViewListener#getView allows you do the same thing and more, and withRowLayoutView will be deprecated. See also: withAdapterSetter(setter)

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.

1.1.9+. a AdapterSetter can be use to customize the DirAdapter .

More information in source code of DirAdapter .

since 1.1.17, DirAdapter.overrideGetView() supports GetViewListener interface.

You can disallow someone enter some special directories.

With withStartFile() , you can limit the root folder.

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.

withOptionResources(@StringRes int createDirRes, @StringRes int deleteRes, @StringRes int newFolderCancelRes, @StringRes int newFolderOkRes)

withOptionStringResources(@Nullable String createDir, @Nullable String delete, @Nullable String newFolderCancel, @Nullable String newFolderOk)

withOptionIcons(@DrawableRes int optionsIconRes, @DrawableRes int createDirIconRes, @DrawableRes int deleteRes)

see the sample codes in demo app.

NOTE:

  1. extra WRITE_EXTERNAL_STORAGE permission should be declared in your AndroidManifest.xml .
  2. we’ll ask the extra runtime permission to WRITE_EXTERNAL_STORAGE on Android M and higher too.

as named as working.

psuedo .. SDCard Storage and .. Primary Storage

since v1.11, external storage will be detected automatically. That means user can switch between internal and external storage by clicking on psuedo folder names.

since the latest patch of v1.14, it allows the chooser dialog title updated by changing directory.

since the latest patch of v1.15, it allows a path string displayed below the title area.

since v1.16, its default value is true.

As a useful complement, customizePathView(callback) allows tuning the path TextView. For example:

since 1.1.17, this can also be done through a custom theme:

you can customize the text of buttons:

For Library Developers

Just fork and build me currently.

Contributions and translations are welcome.

feel free to make a new issue.

many peoples report or contribute to improve me, but only a few of them be put here — it’s hard to list all.

This project exists thanks to all the people who contribute. [Contribute].

Become a financial contributor and help us sustain our community. [Contribute]

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

Источник

Saving Files

This lesson teaches you to

You should also read

Android uses a file system that’s similar to disk-based file systems on other platforms. This lesson describes how to work with the Android file system to read and write files with the File APIs.

A File object is suited to reading or writing large amounts of data in start-to-finish order without skipping around. For example, it’s good for image files or anything exchanged over a network.

Читайте также:  Vice city cleo android

This lesson shows how to perform basic file-related tasks in your app. The lesson assumes that you are familiar with the basics of the Linux file system and the standard file input/output APIs in java.io .

Choose Internal or External Storage

All Android devices have two file storage areas: «internal» and «external» storage. These names come from the early days of Android, when most devices offered built-in non-volatile memory (internal storage), plus a removable storage medium such as a micro SD card (external storage). Some devices divide the permanent storage space into «internal» and «external» partitions, so even without a removable storage medium, there are always two storage spaces and the API behavior is the same whether the external storage is removable or not. The following lists summarize the facts about each storage space.

  • It’s always available.
  • Files saved here are accessible by only your app by default.
  • When the user uninstalls your app, the system removes all your app’s files from internal storage.

Internal storage is best when you want to be sure that neither the user nor other apps can access your files.

  • It’s not always available, because the user can mount the external storage as USB storage and in some cases remove it from the device.
  • It’s world-readable, so files saved here may be read outside of your control.
  • When the user uninstalls your app, the system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() .

External storage is the best place for files that don’t require access restrictions and for files that you want to share with other apps or allow the user to access with a computer.

Tip: Although apps are installed onto the internal storage by default, you can specify the android:installLocation attribute in your manifest so your app may be installed on external storage. Users appreciate this option when the APK size is very large and they have an external storage space that’s larger than the internal storage. For more information, see App Install Location.

Obtain Permissions for External Storage

To write to the external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:

Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

However, if your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.

You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory.

Save a File on Internal Storage

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir() Returns a File representing an internal directory for your app. getCacheDir() Returns a File representing an internal directory for your app’s temporary cache files. Be sure to delete each file once it is no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1MB. If the system begins running low on storage, it may delete your cache files without warning.

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here’s how to write some text to a file:

Or, if you need to cache some files, you should instead use createTempFile() . For example, the following method extracts the file name from a URL and creates a file with that name in your app’s internal cache directory:

Note: Your app’s internal storage directory is specified by your app’s package name in a special location of the Android file system. Technically, another app can read your internal files if you set the file mode to be readable. However, the other app would also need to know your app package name and file names. Other apps cannot browse your internal directories and do not have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.

Save a File on External Storage

Because the external storage may be unavailable—such as when the user has mounted the storage to a PC or has removed the SD card that provides the external storage—you should always verify that the volume is available before accessing it. You can query the external storage state by calling getExternalStorageState() . If the returned state is equal to MEDIA_MOUNTED , then you can read and write your files. For example, the following methods are useful to determine the storage availability:

Читайте также:  Seagull assistant для андроид

Although the external storage is modifiable by the user and other apps, there are two categories of files you might save here:

Public files Files that should be freely available to other apps and to the user. When the user uninstalls your app, these files should remain available to the user.

For example, photos captured by your app or other downloaded files.

Private files Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don’t provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app’s external private directory.

For example, additional resources downloaded by your app or temporary media files.

If you want to save public files on the external storage, use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES . For example:

If you want to save files that are private to your app, you can acquire the appropriate directory by calling getExternalFilesDir() and passing it a name indicating the type of directory you’d like. Each directory created this way is added to a parent directory that encapsulates all your app’s external storage files, which the system deletes when the user uninstalls your app.

For example, here’s a method you can use to create a directory for an individual photo album:

If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null . This returns the root directory for your app’s private directory on the external storage.

Remember that getExternalFilesDir() creates a directory inside a directory that is deleted when the user uninstalls your app. If the files you’re saving should remain available after the user uninstalls your app—such as when your app is a camera and the user will want to keep the photos—you should instead use getExternalStoragePublicDirectory() .

Regardless of whether you use getExternalStoragePublicDirectory() for files that are shared or getExternalFilesDir() for files that are private to your app, it’s important that you use directory names provided by API constants like DIRECTORY_PICTURES . These directory names ensure that the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES are categorized by the system media scanner as ringtones instead of music.

Query Free Space

If you know ahead of time how much data you’re saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace() . These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.

However, the system does not guarantee that you can write as many bytes as are indicated by getFreeSpace() . If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it’s probably safe to proceed. Otherwise, you probably shouldn’t write to storage.

Note: You aren’t required to check the amount of available space before you save your file. You can instead try writing the file right away, then catch an IOException if one occurs. You may need to do this if you don’t know exactly how much space you need. For example, if you change the file’s encoding before you save it by converting a PNG image to JPEG, you won’t know the file’s size beforehand.

Delete a File

You should always delete files that you no longer need. The most straightforward way to delete a file is to have the opened file reference call delete() on itself.

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile() :

Note: When the user uninstalls your app, the Android system deletes the following:

  • All files you saved on internal storage
  • All files you saved on external storage using getExternalFilesDir() .

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

Источник

Оцените статью