You are on page 1of 17

MOBILE APPLICATION DEVELOPMENT

UNIT-III
Data Persistence
DATA STORAGE IN ANDROID
 Persistence : Saving the state of an object in a stable storage area.
 Android provides several storage options for Private and Public
data depending on space requirements
They are
1. Shared Preferences - stores private primitive data in terms of
key-value pair
2. Files

- Stores private data on the device memory


- Stores public data on the shared external
storage
3. SQLite database :stores structured data in private database
4. Network connection : Stores data on the server with your own
network
DATA STORAGE IN ANDROID
 Shared Preferences are lightweight data storage
mechanism
 primarily for saving application settings and user information

 Standard Java File I/O (plus Android helper methods)

 save files directly on the device

 can use both internal and external storage

 SQLite Databasestore

 structured application data in a private database

 full relational database capability

 Content Provider make private data available to other


applications
 exposes read/write access to application data
SHARED PREFERENCES
 The Shared Preferences interface (in package android.content)
provides a general framework that allows you to save and
retrieve persistent key-value pairs of primitive data types and
strings.

 similar to saving data in a Bundle

 Can be used to save the following data types

 boolean, float ,int , long ,String

 Shared preference data will persist across user sessions even if


the application is killed.
EXAMPLES OF DATA STORED IN
SHARED PREFERENCES
 user name – password
 address – high score

An application can have multiple sets of application


preferences, where each set has a name.
Preferences can be stored at the activity level or the
application level.
In general, they are not shared outside the application.
Application preferences are stored in XML files in the
Android file system as follows
:/data/data/<package name>/shared_prefs/<pref filename>.
OBTAINING A SHAREDPREFERENCES
OBJECT
 Two methods that return a SharedPreferences object:

 getSharedPreferences(String name, int mode)


Use if you need multiple preferences files identified by name.
Name is specified as the first parameter.
If a preferences file by this name does not exist, it will be created when you
retrieve an editor.
Preferences can be accessed by all activities in the application.

 getPreferences(int mode)
Use if you need only one preferences file for your Activity.
Only one preferences file for an Activity – don't supply a name.
Calls method getSharedPreferences(String, int) passing in this activity’s
class name as the preferences name.
Preferences are not shared with other activities in the application.
SHARED PREFERENCE MODES
 MODE_PRIVATE created file can be accessed only by the calling
application generally the only preference mode that you should use

 MODE_WORLD_READABLE (deprecated in API level 17)other


applications have read access to the created file

 MODE_WORLD_WRITEABLE (deprecated in API level 17)other


applications have write access to the created file

 MODE_MULTI_PROCESS used if multiple processes are mutating the


same SharedPreferences file always on in apps targeting Gingerbread
(Android 2.3) and below, and off by default in later versions
WRITING/READING SHARED
PREFERENCES
 To write shared preference values:Call edit() to get a
SharedPreferences.Editor.
 Add values with editor “put” methods such as
putBoolean() and putString().
 Commit the new values with apply() or commit().

 To read shared preference values:

Use SharedPreferences “get” methods such as


getBoolean() and getString().
 The “get” methods have two parameters the preference
key string and a default value to return if the preference
is undefined
SELECTED METHODS FOR
RETRIEVING SHARED PREFERENCES
in interface SharedPreferences
 boolean getBoolean(String key, boolean defValue)

 float getFloat(String key, float defValue)

 int getInt(String key, int defValue)

 long getLong(String key, long defValue)

 String getString(String key, String defValue)

 Set<String> getStringSet(String key, Set<String> defValues)


SELECTED METHODS FOR SAVING
SHARED PREFERENCES
 in interface SharedPreferences.Editor
 void apply()

 boolean commit()

 SharedPreferences.Editor putBoolean(String key, boolean value)

 SharedPreferences.Editor putFloat(String key, float value)

 SharedPreferences.Editor putInt(String key, int value)

 SharedPreferences.Editor putLong(String key, long value)

 SharedPreferences.Editor putString(String key, String value)

 SharedPreferences.Editor putStringSet(String key, Set<String>


values)
 SharedPreferences.Editor remove(String key)
DIFFERENCES BETWEEN METHODS
APPLY() AND COMMIT()
 commit() method returns a boolean value to indicate if
the new values were successfully written to persistent
storage.
 Writes its preferences out to persistent storage
synchronously (can block the UI thread)
 apply() Commits its changes to the in-memory
SharedPreferences immediately but starts an
asynchronous commit to disk.
does not block the UI thread, but you won’t be notified
of any failures.
Use apply() if you don't care about the return value and
you’re using this from your application’s UI thread.
EXAMPLE: SHARED PREFERENCES
public static final String PREFS_NAME = "MyPrefsFile";
//Create shared preferences
SharedPreferences settings
=getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", silentMode);
// Commit the edits!
editor.apply();
//Retrieve shared preferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
boolean silentMode =settings.getBoolean("silentMode", false);a
boolean variable
SHAREDPREFERENCES APIS VERSUS
THE PREFERENCE APIS
 The SharedPreferences APIs discussed in the previous
slides are only for reading and writing key-value pairs
 The Preference APIs are for building a user interface for
application settings that is consistent with the user
experience in other Android applications, including
system settings.
 The Preference APIs use SharedPreferences as their
implementation to save the application settings.
FILE HANDLING – INTERNAL STORAGE

 Internal storage is the storage of the private data on the device memory.
 By default these files are private and are accessed by only your
application and get deleted , when user delete your application.

Writing file
 In order to write some data in the file, call the openFileOutput() method
with the name of the file and the mode.
syntax is given below −
 FileOutputStream fOut = openFileOutput("file name
here",MODE_WORLD_READABLE);
 The method openFileOutput() returns an instance of FileOutputStream.

After that you can call write method to write data on the file.
String str = "data";
fOut.write(str.getBytes());
READING FILE

 call the openFileInput() method with the name of the


file. It returns an instance of FileInputStream. 

 FileInputStream fin = openFileInput(file);


Ex-code:
int c;
String temp="";
while( (c = fin.read()) != -1)
{ temp = temp + Character.toString((char)c); }
fin.close();
FILEOUTPUTSTREAM -METHODS
FileOutputStream(File file, boolean append)
 This method constructs a new FileOutputStream that
writes to file.
getChannel()
 This method returns a write-only FileChannel that shares
its position with this stream
getFD()
 This method returns the underlying file descriptor

write(byte[] buffer, int byteOffset, int byteCount)


 This method Writes count bytes from the byte array
buffer starting at position offset to this stream
FILEOUTPUTSTREAM -METHODS
 available()
This method returns an estimated number of bytes that can
be read or skipped without blocking for more input
 getChannel()

This method returns a read-only FileChannel that shares its


position with this stream
getFD()
 This method returns the underlying file descriptor

read(byte[] buffer, int byteOffset, int byteCount)


 This method reads at most length bytes from this stream
and stores them in the byte array b starting at offset

You might also like