You are on page 1of 44

Android Developer Fundamentals V2

Preferences
and settings

Lesson 9

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 1
License.
9.0 Data Storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 2
License.
Contents

● Android File System


● Internal Storage
● External Storage
● SQLite Database
● Other Storage Options

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 3
License.
Storage
Options

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 4
License.
Storing data

● Shared Preferences—Private primitive data in key-value pairs


● Internal Storage—Private data on device memory
● External Storage—Public data on device or external storage
● SQLite Databases—Structured data in a private database
● Content Providers—Store privately and make available publicly

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 5
License.
Storing data beyond Android

● Network Connection—On the web with your own server


● Cloud Backup—Back up app and user data in the cloud
● Firebase Realtime Database—Store and sync data with
NoSQL cloud database across clients in realtime

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 6
License.
Files

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 7
License.
Android File System

● External storage -- Public directories


● Internal storage -- Private directories for just your app

Apps can browse the directory structure


Structure and operations similar to Linux and java.io

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 8
License.
Internal storage
● Always available
● Uses device's filesystem
● Only your app can access files, unless explicitly set to be
readable or writable
● On app uninstall, system removes all app's files from
internal storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 9
License.
External storage

● Not always available, can be removed


● Uses device's file system or physically external storage like
SD card
● World-readable, so any app can read
● On uninstall, system does not remove files private to app

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 10
License.
When to use internal/external storage
Internal is best when
● you want to be sure that neither the user nor other apps
can access your files
External is best for files that
● don't require access restrictions and for
● you want to share with other apps
● you allow the user to access with a computer

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 11
License.
Save user's file in shared storage

● Save new files that the user acquires through your app to
a public directory where other apps can access them and
the user can easily copy them from the device
● Save external files in public directories

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 12
License.
Internal Storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 13
License.
Internal Storage

● Uses private directories just for your app


● App always has permission to read/write
● Permanent storage directory—getFilesDir()
● Temporary storage directory—getCacheDir()

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 14
License.
Creating a file

File file = new File(


context.getFilesDir(), filename);

Use standard java.io file operators or streams


to interact with files

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 15
License.
Creating a file
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:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace(); }

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 16
License.
Creating a file
if you need to cache some files, instead use createTempFile(). For example, the following method
extracts the filename from a URL and creates a file with that name in your app's internal cache directory:

public File getTempFile(Context context, String url) {


File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
} return file;}

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 17
License.
External
Storage

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 18
License.
External Storage
• Use external storage for files that should be permanently stored, even if your
app is uninstalled, and be available freely to other users and apps, such as
pictures, drawings, or documents made by your app.
• Some private files that are of no value to other apps can also be stored on
external storage.
• Such files might be additional downloaded app resources, or temporary media
files. Make sure you delete those when your app is uninstalled.

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 19
License.
External Storage
● On device or SD card
● Set permissions in Android Manifest
○ Write permission includes read permission

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
This work is licensed under a Creative
Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 20
License.
Availability of 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:

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 21
License.
Whether external storage is mounted
/* Checks if external storage is available to at least read
/* Checks if external storage is available for read and
write */ */
public boolean isExternalStorageWritable() { public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
String state =Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{ if (Environment.MEDIA_MOUNTED.equals(state) ||
return true; Environment.MEDIA_MOUNTED_READ_ONLY.equals(sta
} return false;}
te)) {
return true;
} return false; }

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 22
License.
Public and private external storage
• External storage is very specifically structured and used by the Android system.
• There are public directories, and private directories specific to your app.

• Each of these file trees has directories identified by system constants.


• For example, any files that you store into the public ringtone directory
DIRECTORY_RINGTONES are available to all other ringtone apps.
• On the other hand, any files you store in a private ringtone directory
DIRECTORY_RINGTONES can, by default, only be seen by your app and are deleted along
with your app.

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 23
License.
Example external public directories
● DIRECTORY_ALARMS and DIRECTORY_RINGTONES
For audio files to use as alarms and ringtones
● DIRECTORY_DOCUMENTS
For documents that have been created by the user
● DIRECTORY_DOWNLOADS
For files that have been downloaded by the user

developer.android.com/reference/android/os/Environment.html
This work is licensed under a Creative
Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 24
License.
Accessing public external directories
1. Get a path getExternalStoragePublicDirectory()
2. Create file

File path = Environment.getExternalStoragePublicDirectory(


Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 25
License.
Getting File Descriptors
To access a private external storage directory, get a path and create a file calling
getExternalFilesDir().
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 26
License.
How much storage left?
● If there is not enough space, throws IOException
● If you know the size of the file, check against space
○ getFreeSpace()
○ getTotalSpace().
● If you do not know how much space is needed
○ try/catch IOException

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 27
License.
Delete files no longer needed

● External storage
myFile.delete();

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

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 28
License.
Do not delete the user's files!
When the user uninstalls your app, your app's private storage
directory and all its contents are deleted
Do not use private storage for content that belongs to the user!
For example
● Photos captured or edited with your app
● Music the user has purchased with your app

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 29
License.
Shared
Preferences
& SQLite
Database

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 30
License.
SQLite Database

● Ideal for repeating or structured data, such as contacts


● Android provides SQL-like database
● Covered in following chapters and practicals
○ SQLite Primer
○ Introduction to SQLite Databases
○ SQLite Data Storage Practical
○ Searching an SQLite Database Practical

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 31
License.
Shared Preferences

● Read and write small amounts of primitive data as


key/value pairs to a file on the device storage

● Covered in later chapter and practical


○ Shared Preferences

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 32
License.
Other Storage
Options

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 33
License.
Use Firebase to store and share data
Store and sync data with the Firebase
cloud database
Data is synced across all clients, and
remains available when your app goes
offline
firebase.google.com/docs/database/

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 34
License.
Firebase Realtime Database

● Connected apps share data


● Hosted in the cloud
● Data is stored as JSON
● Data is synchronized in realtime to
every connected client

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 35
License.
Network Connection

● You can use the network (when it's available) to store and
retrieve data on your own web-based services

● Use classes in the following packages


○ java.net.*
○ android.net.*

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 36
License.
Backing up data

● Auto Backup for 6.0 (API level 23) and higher


● Automatically back up app data to the cloud
● No code required and free
● Customize and configure auto backup for your app

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 37
License.
Backing up data
• When a user installs your app on a new device, or reinstalls your app on one (for example, after a
factory reset), the system automatically restores the app data from the cloud.

• The automatic backup feature preserves the data your app creates on a user device by uploading it
to the user's Google Drive account and encrypting it.

• There is no charge to you or the user for data storage, and the saved data does not count towards
the user's personal Google Drive quota.

• Each app can store up to 25MB.

• Once its backed-up data reaches 25MB, the app no longer sends data to the cloud.

• If the system performs a data restore, it uses the last data snapshot that the app had sent to the
cloud.

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 38
License.
Automatic Backup Conditions
Automatic backups occur when the following conditions are met:
• The device is idle.
• The device is charging.
• The device is connected to a Wi-Fi network.
• At least 24 hours have elapsed since the last backup

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 39
License.
Backup API for Android 5.1 (API level 22)

1. Register for Android Backup Service to get a Backup Service Key


2. Configure Manifest to use Backup Service
3. Create a backup agent by extending the BackupAgentHelper class
4. Request backups when data has changed
More info and sample code: Using the Backup AP and Data Backup

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 40
License.
Learn more about files

● Saving Files
● getExternalFilesDir() documentation and code samples
● getExternalStoragePublicDirectory() documentation and code samples
● java.io.File class
● Oracle's Java I/O Tutorial

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 41
License.
Learn more about backups

● Configuring Auto Backup for Apps


● Using the Backup API
● Data Backup

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 42
License.
What's next?

● Concept Chapter: 9.0 Data Storage


● No practical, this was an overview lecture

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 43
License.
END

This work is licensed under a Creative


Android Developer Fundamentals V2 Data storage Commons Attribution 4.0 International 44
License.

You might also like