Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this lesson, you’ll learn how to store data in files. You’ll learn about internal and external storage. You’ll also learn about permissions and shared and scoped storage.

Reading and Writing Files

Android uses a file system like other disk-based file systems. The system provides the following options for you to save your app data:

App-Specific Storage

App-specific storage can be internal or external. Internal storage is always available to your app, and it’s always accessible. External storage isn’t always available, and it may be removed by the user or other apps. Always use internal storage when you don’t want the user of your app or other apps to access the files.

Internal Storage

Internal storage is private to your app. The Android system creates a directory for each app. The directory is named after the app’s package name. When a user uninstalls your app, the system deletes all the files in the internal storage directory.

External Storage

External storage can either be a dedicated partition on the devices or a removable storage medium. This means that external storage isn’t always available. For example, a user can mount a removable SD card on their phone and remove it. If you want to use external storage, you must check the available external storage directories and if the files exist before using them. To access the external storage directories, you use the context.getExternalFilesDir() function. This function returns a File object representing the external storage directory. You can then use this object to create files and directories in the external storage directory.

Permissions

To declare permissions, you must add the <uses-permissions> element in your app’s AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  package="com.kodeco.android.devscribe">
  <uses-permission .../>

  ...
</manifest>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Using Shared Storage and Scoped Storage

Shared storage is for data that should be accessible to other apps even when your app is uninstalled. Shared storage includes media files, documents, and other files that the user expects to be accessible to other apps. Android also provides APIs to store and access the following types of files in shared storage:

See forum comments
Download course materials from Github
Previous: Introduction Next: Conclusion