0% found this document useful (0 votes)
8 views

04.1 Data Persistence - Preferences

Uploaded by

henil1872
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

04.1 Data Persistence - Preferences

Uploaded by

henil1872
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Data Persistence

Preferences
Table of Content
Introduction

What is Data Persistence?

Shared Preferences

2
Introduction
Why storing and retrieving data in mobile applications is important ?

- User Experience
- Offline Functionality
- Data Integrity
- Personalization
- Performance Optimization
- Data Backup and Restoration
- Cross-Device Synchronization

3
Introduction (Cont.)
Data persistence in Android refers to the ability to store and retrieve data beyond the
lifetime of an application.

It allows the app to save and access data even after the app is closed or the device is
restarted.

Data persistence is crucial for

- maintaining user preferences,


- settings, app state, and other important information.

4
Introduction (Cont.)
Android provides various mechanisms for data persistence, including:

● Shared Preferences
● Internal Storage
● External Storage
● SQLite Database
● Content Providers
● Network and Cloud-Based Storage

5
Introduction (Cont.)
Different data persistence mechanisms have their own strengths and use cases.

The choice of which mechanism to use depends on following factors:

- Type of data,
- Data size,
- Security requirements
- App's specific needs.

6
What is Data Persistence?
Data Persistence allows users to save their settings, preferences, and progress.

For E.g.:

● Settings and Preferences


● User Accounts and Credentials
● Progress and State
● Forms and Input Data

Data Persistence is important as users expects to reuse the data in future.

7
Shared Preferences
● Shared Preferences is a lightweight data storage mechanism
● It allows applications to store and retrieve key-value pairs persistently.
● It is simple & convenient to store small amount of data
● Data is stored in XML file in the directory

data/data/<package-name>/shared-prefs

● It only allows you to store primitive data types


- booleans , Floats, longs, Ints & Strings

8
Shared Preferences (Cont.)
Key features of Shared Preferences:

● Key-Value Storage
● Application-Specific Storage
● Persistent Storage
● XML-Based Storage
● Easy API Access
● Lightweight and Efficient

9
Shared Preferences (Cont.)
● We can save the preferences data either in single or multiple files based on our
requirements.
● To get values from the shared preferences we use:
- getPreferences() method (for single file)
- getSharedPreferences() method (for Multiple files)

10
Shared Preferences (Cont.)
getPreferences()

- This method is for activity level preferences


- Each activity will have its own preference file by default
- this method retrieves a default shared preference file that belongs to the activity.

For single Shared preference file we need to initialize the SharedPreferences object by
using getPreferences() method like as shown below.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

11
Shared Preferences (Cont.)
getSharedPreferences()

- This method is useful to get the values from multiple shared preference files
- Filename is passed as a parameter to access data from the specific file

For single Shared preference file we need to initialize the SharedPreferences object by
using getPreferences() method like as shown below.
SharedPreferences sharedPref =
getSharedPreferences("filename1",Context.MODE_PRIVATE);

12
Shared Preferences (Cont.)
To control access permission to the files we have following modes:

MODE_PRIVATE

- Private only to the application

MODE_WORLD_READABLE

- all applications can read XML file

MODE_WORLD_WRITEABLE

- all applications can write XML file

13
Shared Preferences (Cont.)
Write to Shared Preferences (Store data)
To store data in a shared preference file, we need an editor to edit and save the changes
in the SharedPreferences object.

14
Shared Preferences (Cont.)
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPref.edit();

editor.putBoolean("keyname",true);

editor.putString("keyname","string value");

editor.putInt("keyname","int value");

editor.putFloat("keyname","float value");

editor.putLong("keyname","long value");

editor.commit(); // to save all the changes we are calling commit()


method.
15
Shared Preferences (Cont.)
Read from Shared Preferences (Retrieve data)
To read or retrieve values from the Shared Preferences file, we need to call methods
such as getInt(), getString(), etc.

16
Shared Preferences (Cont.)
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);

pref.getString("keyname",null);

pref.getInt("keyname",0);

pref.getFloat("keyname",0);

pref.getBoolean("keyname",true);

pref.getLong("keyname",0);

17
Shared Preferences (Cont.)
Deleting from Shared Preferences
To delete values from the Shared Preferences file, we need to call remove() method by
providing the key for the value which we want to delete

18
Shared Preferences (Cont.)
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);

SharedPreferences.Editor editor = pref.edit();

editor.remove("keyname");

editor.commit();

19
Shared Preferences (Cont.)
Clearing the Shared Preferences
We can clear all the data from Shared Preferences file using a clear() method

20
Shared Preferences (Cont.)
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);

SharedPreferences.Editor editor = pref.edit();

editor.clear();

editor.commit();

21
Shared Preferences Internal Structure
● Shared preferences internally has an in-memory storage on the top of disk storage
● Every operation goes through in-memory storage first & then to the disk.
● In-memory storage is basically a HashMap which allows O(1) time complexity for
all operations.

In-Memory Disk

HashMap XML
22
Shared Preferences (Cont.)
Save Data via Commit

● It saves data in to in-memory storage first & then synchronously writes it to the
disk.
● Since IO operation is involved, main thread is blocked until the data is written to
the disk.
● Due to write operation is synchronous, success status is returned as a boolean.
● Using the return value you can verify the operation is successful or not.
Val result = pref.edit().putString(key, “value”).commit()

23
Shared Preferences (Cont.)
Save Data via Commit
Val result = pref.edit().putString(key, “value”).commit()

putString(key, “value”) commit()


In-Memory Disk

HashMap XML

24
Shared Preferences (Cont.)
Save Data via apply

● It saves data in to in-memory storage first & then asynchronously writes it to the
disk.
● Since IO operation is involved, main thread is not blocked.
● Due to write operation is asynchronous, success status is not returned .
● So you cannot verify the operation is successful or not.
pref.edit().putString(key, “value”).apply()

25
Shared Preferences (Cont.)
Save Data via apply
pref.edit().putString(key, “value”).apply()

putString(key, “value”) apply()


In-Memory Disk

Worker Thread

26
Shared Preferences (Cont.)
Get the data

● All get operations are done through in-memory storage


● All IO operation are avoided.
● As all operations go through In-memory first, surely you will get the latest value.
Val result = pref.getString(key, null)

27
Shared Preferences (Cont.)
Get the data
Val result = pref.getString(key, null)

pref.getString(key, null)
In-Memory Disk

HashMap XML

28
Shared Preferences (Cont.)
Some use case of Shared Preferences

● First time: if user is using your app


● Updates: checks when your app was last updated
● Credentials: remembers the user details
● Settings: remembers user settings
● Location Catching

29
Shared Preferences (Cont.)
Our Example:

Save load

next back

Shared
Preferences
Main Activity Activity B

30
Shared Preferences Example (Code)
Activity_main.xml file

AndroidManifest.xml file

MainActivity.java file

validateActivity.java file

Validate.xml file

31

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy