UNIT 4:
Persistent Storage
Persistent storage:
Persistent storage refers to the ability of a mobile application to store data in a way that survives even after
the application is closed or the device is restarted. In mobile development, persistent storage is crucial for
saving user data, settings, and other important information.
Types of Persistent Storage:
1. Internal Storage: Internal storage refers to the storage space allocated to an app's private directory. This
storage is not accessible to other apps, and data stored here is deleted when the app is uninstalled.
2. External Storage: External storage refers to storage space that can be accessed by other apps and the user.
This can include SD cards or other external storage devices.
3. Shared Preferences: Shared Preferences is a simple key-value store that allows you to save and retrieve
small amounts of data, such as strings, integers, and booleans.
4. SQLite Database: SQLite is a lightweight relational database that allows you to store and manage larger
amounts of data in a structured way.
5. Room Persistence Library: Room is a persistence library that provides an abstraction layer over SQLite,
making it easier to work with databases in Android apps.
Benefits of Persistent Storage:
1. Data Persistence: Persistent storage allows data to be saved even after the app is closed or the device is
restarted.
2. Improved User Experience: By saving user data and settings, persistent storage can improve the user
experience by reducing the need for users to re-enter data or reconfigure settings.
3. Offline Support: Persistent storage can enable offline support for apps, allowing users to access and
interact with data even when they don't have an internet connection.
Best Practices for Persistent Storage:
1. Use the Right Storage Option: Choose the right storage option based on the type and amount of data you
need to store.
2. Encrypt Sensitive Data: Encrypt sensitive data to protect it from unauthorized access.
3. Handle Storage Limitations: Handle storage limitations and errors gracefully, and provide feedback to
users when storage space is running low.
4. Test Thoroughly: Test your app's storage functionality thoroughly to ensure it works correctly and
efficiently.
By understanding persistent storage options and best practices, mobile developers can create apps that
provide a seamless and efficient user experience.
Files in Persistent Storage:
Files are a fundamental component of persistent storage in mobile development. They allow apps to store
and retrieve data in a structured and organized way. Here are some key aspects of files in persistent storage:
Types of Files:
1. Internal Files: Internal files are stored in the app's private directory and are not accessible to other apps.
2. External Files: External files are stored in a public directory and can be accessed by other apps and the
user.
File Operations:
1. Creating Files: You can create files using the File class or the openFileOutput() method.
2. Reading Files: You can read files using the FileInputStream class or the openFileInput() method.
3. Writing Files: You can write files using the FileOutputStream class or the openFileOutput() method.
4. Deleting Files: You can delete files using the delete() method.
Best Practices:
1. Use Application-Specific Directories: Store files in application-specific directories to keep them organized
and secure.
2. Handle File Errors: Handle file errors and exceptions properly to ensure your app remains stable and
secure.
3. Use Efficient File Operations: Use efficient file operations to minimize the impact on app performance
and battery life.
File Storage Options:
1. Internal Storage: Internal storage is a private storage area for your app's files.
2. External Storage: External storage is a public storage area that can be accessed by other apps and the user.
3. Cache Directory: The cache directory is a special directory for storing temporary files that can be deleted
by the system when storage space is low.
Security Considerations:
1. File Permissions: Be mindful of file permissions and ensure that sensitive data is stored securely.
2. Data Encryption: Consider encrypting sensitive data stored in files to protect it from unauthorized access.
Using Application-Specific Folders and Files:
Application-specific folders and files are a crucial part of mobile development, allowing apps to store and
retrieve data in a structured and organized way. Here are some key aspects of using application-specific
folders and files:
Benefits:
1. Data Organization: Application-specific folders help keep data organized and easy to manage.
2. Data Security: By storing data in application-specific folders, you can ensure that sensitive data is
protected from unauthorized access.
3. Data Persistence: Application-specific folders provide a way to store data that persists even after the app
is closed or the device is restarted.
Internal Storage:
1. getFilesDir(): This method returns the directory where your app can store its files.
2. openFileOutput(): This method opens a file output stream for writing to a file in your app's internal
storage directory.
External Storage:
1. getExternalFilesDir(): This method returns the directory where your app can store its files on external
storage.
2. Environment.getExternalStorageDirectory(): This method returns the root directory of external storage.
Best Practices:
1. Use Application-Specific Directories: Store files in application-specific directories to keep them organized
and secure.
2. Handle Storage Limitations: Handle storage limitations and errors properly to ensure your app remains
stable and functional.
3. Use Efficient File Operations: Use efficient file operations to minimize the impact on app performance
and battery life.
Example:
// Writing to a file in internal storage
String filename = "example.txt";
String fileContents = "Hello, World!";
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(fileContents.getBytes());
fos.close();
// Reading from a file in internal storage
FileInputStream fis = openFileInput(filename);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
String fileContents = new String(buffer);
fis.close();
Creating Files in Persistent Storage:
Internal Storage:
1. Get the File Directory: Use the getFilesDir() method to get the directory where your app can store its files.
2. Create a File: Use the File class to create a new file in the directory.
3. Write to the File: Use a FileOutputStream to write data to the file.
Example:
// Create a file in internal storage
String filename = "example.txt";
String fileContents = "Hello, World!";
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(fileContents.getBytes());
fos.close();
External Storage:
1. Get the External Storage Directory: Use the getExternalFilesDir() method to get the directory where your
app can store its files on external storage.
2. Create a File: Use the File class to create a new file in the directory.
3. Write to the File: Use a FileOutputStream to write data to the file.
Example:
// Create a file in external storage
File directory = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File file = new File(directory, "example.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(fileContents.getBytes());
fos.close();
Advantages:
1. Handle Storage Limitations: Handle storage limitations and errors properly to ensure your app remains
stable and functional.
2. Use Efficient File Operations: Use efficient file operations to minimize the impact on app performance
and battery life.
3. Secure Sensitive Data: Secure sensitive data by using encryption or other security measures.
Reading Data from Files in Persistent Storage:
Reading data from files in persistent storage is a crucial aspect of mobile development, allowing apps to
retrieve and use stored data. Here are the steps to read data from files in persistent storage:
Internal Storage:
1. Get the File: Use the File class to get the file you want to read from.
2. Create a FileInputStream: Use the openFileInput() method to create a FileInputStream object.
3. Read the File: Use the FileInputStream to read the file contents.
Example:
// Read from a file in internal storage
String filename = "example.txt";
FileInputStream fis = openFileInput(filename);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
String fileContents = new String(buffer);
fis.close();
External Storage:
1. Get the External Storage Directory: Use the getExternalFilesDir() method to get the directory where your
app's files are stored on external storage.
2. Create a File: Use the File class to create a File object representing the file you want to read.
3. Create a FileInputStream: Use a FileInputStream to read the file contents.
Example:
// Read from a file in external storage
File directory = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File file = new File(directory, "example.txt");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
String fileContents = new String(buffer);
fis.close();
Advantages:
1. Handle File Errors: Handle file errors and exceptions properly to ensure your app remains stable and
functional.
2. Use Efficient File Operations: Use efficient file operations to minimize the impact on app performance
and battery life.
3. Validate File Contents: Validate the contents of the file to ensure they are in the expected format.
Shared Preferences in Persistent Storage:
Shared Preferences is a simple key-value store that allows you to save and retrieve small amounts of data,
such as strings, integers, and booleans, in a mobile app. Here's how to use Shared Preferences in persistent
storage:
Benefits:
1. Easy to Use: Shared Preferences is a straightforward and easy-to-use storage solution.
2. Lightweight: Shared Preferences is a lightweight storage solution that doesn't require a lot of overhead.
3. Private Data: Shared Preferences stores data in a private file that is not accessible to other apps.
Using Shared Preferences:
1. Get a SharedPreferences Object: Use the getSharedPreferences() method to get a SharedPreferences
object.
2. Edit the SharedPreferences: Use the edit() method to get a SharedPreferences.Editor object.
3. Put Data: Use the putString(), putInt(), putBoolean(), etc. methods to put data into the SharedPreferences.
4. Commit the Changes: Use the commit() or apply() method to commit the changes.
Example:
// Save data to SharedPreferences
SharedPreferences prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "JohnDoe");
editor.putInt("age", 30);
editor.apply();
// Retrieve data from SharedPreferences
String username = prefs.getString("username", "");
int age = prefs.getInt("age", 0);
Advantages:
1. Use Meaningful Keys: Use meaningful keys to store data in SharedPreferences.
2. Handle Default Values: Handle default values properly when retrieving data from SharedPreferences.
3. Use apply() Instead of commit(): Use the apply() method instead of commit() to avoid blocking the main
thread.
Listing Contents of a Directory:
To list the contents of a directory in mobile development, you can use the listFiles() method of the File class.
Here's how to do it:
Example:
// Get the directory
File directory = getFilesDir();
// List the contents of the directory
File[] files = directory.listFiles();
// Loop through the files and print their names
for (File file : files) {
Log.d("File", file.getName());
}
Listing Shared Preferences:
Shared Preferences files are stored in a specific directory, and you can list them like any other file. However,
it's generally not necessary to list Shared Preferences files manually, as you can access them using the
getSharedPreferences() method.
Example:
// Get the SharedPreferences directory
File sharedPrefsDir = new File(getFilesDir().getParent() + "/shared_prefs");
// List the SharedPreferences files
File[] sharedPrefsFiles = sharedPrefsDir.listFiles();
// Loop through the files and print their names
for (File file : sharedPrefsFiles) {
Log.d("SharedPreferences", file.getName());
Advantages:
1. Handle Null Pointer Exceptions: Make sure to handle null pointer exceptions when working with files and
directories.
2. Check File Existence: Check if a file exists before trying to access it.
3. Use Efficient File Operations: Use efficient file operations to minimize the impact on app performance
and battery life.
Creating Shared Preferences:
Shared Preferences is a simple key-value store that allows you to save and retrieve small amounts of data in
a mobile app. Here's how to create Shared Preferences:
Step 1: Get a Shared Preferences Object
To create Shared Preferences, you need to get a SharedPreferences object using the getSharedPreferences()
method. This method takes two parameters: the name of the Shared Preferences file and the mode.
SharedPreferences prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
Step 2: Edit the SharedPreferences
To add or modify data in the Shared Preferences, you need to get a SharedPreferences.Editor object using
the edit() method.
SharedPreferences.Editor editor = prefs.edit();
Step 3: Put Data
You can put data into the Shared Preferences using the putString(), putInt(), putBoolean(), etc. methods.
editor.putString("username", "JohnDoe");
editor.putInt("age", 30);
Step 4: Commit the Changes
Finally, you need to commit the changes using the commit() or apply() method.
editor.apply();
Example:
// Create SharedPreferences
SharedPreferences prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// Put data
editor.putString("username", "JohnDoe");
editor.putInt("age", 30);
// Commit the changes
editor.apply();
Modes:
- Context.MODE_PRIVATE: This is the default mode, which means the Shared Preferences file is private to
your app.
- Context.MODE_WORLD_READABLE: This mode allows other apps to read the Shared Preferences file.
- Context.MODE_WORLD_WRITEABLE: This mode allows other apps to write to the Shared Preferences
file.
Saving and Retrieving Data using Shared Preferences:
Shared Preferences is a simple key-value store that allows you to save and retrieve small amounts of data in
a mobile app. Here's how to save and retrieve data using Shared Preferences:
Saving Data:
1. Get a SharedPreferences Object:
Use the getSharedPreferences() method to get a SharedPreferences object.To save data using Shared
Preferences, you need to get a SharedPreferences object. You can do this by calling the
getSharedPreferences() method on a Context object, such as an Activity.
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE)
2. Edit the SharedPreferences:
Use the edit() method to get a SharedPreferences.Editor object.
To save data, you need to edit the SharedPreferences object using the edit() method. This returns a
SharedPreferences.Editor object that you can use to add, remove, or modify data.
SharedPreferences.Editor editor = sharedPreferences.edit();
3. Put Data:
Use the putString(), putInt(), putBoolean(), etc. methods to put data into the SharedPreferences.
You can save data using various methods, such as putString(), putInt(), and putBoolean().
editor.putString("name", "John Doe");
editor.putInt("age", 30);
editor.putBoolean("isLoggedIn", true);
4. Commit the Changes:
Use the commit() or apply() method to commit the changes.
editor.apply(); // or editor.commit();
Example:
// Save data to SharedPreferences
SharedPreferences prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "JohnDoe");
editor.putInt("age", 30);
editor.apply();
Retrieving Data:
1. Get a SharedPreferences Object: Use the getSharedPreferences() method to get a SharedPreferences
object.
2. Get Data: Use the getString(), getInt(), getBoolean(), etc. methods to get data from the SharedPreferences.
Example:
// Retrieve data from SharedPreferences
SharedPreferences prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
String username = prefs.getString("username", "");
int age = prefs.getInt("age", 0);
Data Types:
- putString(): Saves a string value.
- putInt(): Saves an integer value.
- putBoolean(): Saves a boolean value.
- putFloat(): Saves a float value.
- putLong(): Saves a long value.
Best Practices:
- Use meaningful keys for your data.
- Handle default values properly when retrieving data.
- Use the apply() method instead of commit() to avoid blocking the main thread.