07 Handout 1
07 Handout 1
Data Storage • A file can be created in either of the two (2) directories:
o Permanent storage: The getFilesDir() method returns
Data Storage Options the absolute path to the directory on the filesystem where
• The data storage options in Android are as follows: files created are stored.
o Shared preferences – key-value pairs that store private o Temporary storage: The getCacheDir() method returns
primitive data. A key-value pair (KVP) is a set of two (2) the absolute path to the application-specific cache directory
linked data items: a key, the unique identifier for some item on the filesystem. This is recommended for small,
of data, and the value, the data that is identified. temporary files totaling less than 1MB. The system will
o Internal storage – device memory where private data is automatically delete files in the cache directory as disk
stored space is needed elsewhere on the device.
o External storage – stores public data • To create a file:
o SQLite databases – private databases used for storing File myFile = new File(context.getFilesDir(), filename);
structured data
o Room persistence library – caches an SQLite database • To write to a file in the internal directory:
locally, and automatically syncs changes to a network String filename = "myfile";
database String string = "Writing!";
o Cloud backup – saves user data in the cloud FileOutputStream outputStream;
o Firebase realtime database – stores and syncs data with
a NoSQL cloud database. Data is synced across all clients try {
in real time and remains available when your app goes outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
offline. outputStream.write(string.getBytes());
o Custom data store – stores preferences in a specific outputStream.close();
storage location using the Preferences API. This library } catch (Exception e) {
manages the user interface and interacts with storage so e.printStackTrace();
that you define only the individual settings that the user can }
configure.
• To access the external storage, indicate a uses-permission
Internal Storage and External Storage attribute in the Android manifest.
• The table below summarizes the comparison between internal • To write to the external storage:
storage and external storage. <uses-permission
Internal Storage External Storage android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Always available Not always available • To read (without writing) the external storage:
The files of an app cannot be Can be accessed by any app <uses-permission
accessed by other apps. android:name="android.permission.READ_EXTERNAL_STORAGE" />
The app's files are removed The app's files can be removed
once the app is uninstalled. using getExternalFilesDir(). • To delete a file: myFile.delete();
It is best to use when you do It is best to use if you want to
not want other users or other share files with other users or
apps to access your files. other apps.