0% found this document useful (0 votes)
7 views54 pages

Module - 5: Persisting Data

The document outlines various methods for persisting data in Android applications, including SharedPreferences, internal and external storage, and SQLite databases. It details how to save and retrieve simple application data, manage user preferences, and handle application instance states. Additionally, it discusses the advantages and disadvantages of each storage method and provides examples of how to implement them in code.

Uploaded by

santamariya474
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)
7 views54 pages

Module - 5: Persisting Data

The document outlines various methods for persisting data in Android applications, including SharedPreferences, internal and external storage, and SQLite databases. It details how to save and retrieve simple application data, manage user preferences, and handle application instance states. Additionally, it discusses the advantages and disadvantages of each storage method and provides examples of how to implement them in code.

Uploaded by

santamariya474
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/ 54

Module – 5

Persisting data

BSC/BCA S6 – S.A
1.Saving simple Application Data

Android provides several options to save persistent application data. Persistent


data persists throughout the application’s life period. Persistent data denotes
information that is infrequently accessed and not likely to be modified. The data
storage option chosen depends on whether the data should be private to the
application or accessible to other applications (and the user) and how much space
the data requires.
Persistent Data storage options in android are the following
SharedPreferences : Store primitive private data as key-value pairs.
Internal Storage : Store private data in the device memory.
External Storage : Store public data on the shared external storage.
SQLite Databases : Store structured data in a private database.
Network connection : Store data on the web with own network server.
Saving States and Preferences

➢ Android offers a robust and flexible framework for dealing with preferences.
➢ Preference is a feature choice the user makes and saves to customize the
application. Example- Setting notification via ringtone or vibration.
➢ The application remembers the choice until the user changes it.

➢ Saved Instance State


➢ Data can also be saved using Saved Instance state.
➢ Advantages of saved instance state
➢ State of the activity is restored if the activity is closed.
➢ Saving data is quick and simple in key-value pairs.
➢ It is useful when device orientation is changed to landscape or portrait.
➢ Disadvantages of saved instance state
➢ Data stored is not persistent i.e. data is lost if the device is restarted.
2. Creating
and Saving Shared Preferences
➢The SharedPreferences class provides a general framework that allows
to save and retrieve persistent key-value pairs.
➢SharedPreferences can be used to save any primitive data such as
boolean, float, int, long, and string.
➢This data will persist across user sessions (even if your application is
killed).
➢To get a SharedPreferences object for the application, use one of two
methods:
❖getSharedPreferences() - Use this if you need multiple
preferences files identified by name, which you specify with the first
parameter.
❖getPreferences() - Use this if you need only one preferences file
for your Activity.
Because this will be the only preferences file for your Activity, you
don't supply a name.
➢Methods used to write values –
➢ Call edit() to get SharedPreferences.Editor.
❖Add values with methods - putBoolean() and putString().
❖Commit the new values - commit().
❖To read values - getBoolean(), getString().

➢ Shared preference data is lost when the user uninstalls the


application or clears the application data from settings.
➢ Android platform stores the application’s shared preferences in
an XML file with private access to the application.
➢ An application may have one(default shared preference of
application) or more Shared preference files(defined with unique
names).
➢The PreferenceManager class provides methods to get access to
preferences stored in a certain file.
➢The following code shows how to access preferences from a certain
file
SharedPreferences sp = getSharedPreferences("Test", Context.MODE_PRIVATE);

➢Preferences should be created private for the application.


➢To create or change preferences you have to call the edit() method.
➢Once the values are changed, call the apply()/ commit() method to
apply changes asynchronously to the file system.
Sr.No Mode & description
1 MODE_APPEND
This will append the new preferences with the already existing
preferences
4 MODE_PRIVATE
By setting this mode, the file can only be accessed using calling
application
5 MODE_WORLD_READABLE
This mode allow other application to read the preferences

6 MODE_WORLD_WRITEABLE
This mode allow other application to write the preferences
Sr. NO Mode & description

1 apply()
It is an abstract method. It will commit your changes back from
editor to the sharedPreference object you are calling

2 clear()
It will remove all values from the editor
3 remove(String key)
It will remove the value whose key has been passed as a
parameter
4 putLong(String key, long value)
It will save a long value in a preference editor

5 putInt(String key, int value)


It will save a integer value in a preference editor

6 putFloat(String key, float value)


It will save a float value in a preference editor
SharedPreferences.Editor edit = sp.edit();
edit.putString("username", "new_value_for_user");
edit.apply();

In Game applications, Every time the user logs in to the application user
should be able to see the username, the last level he was in coupled with
.the high score that user has made. This is an example of persistent data
storage.
• Also, the application has to maintain user settings preferences, if the
user has turned on/off the music of the game or notifications.
•But when it comes to storing of large data then shared preference is not the
right choice. It fails to store large data.
• Do not opt for shared preferences to store Images, videos, Audio files,
large text files, spreadsheets or presentations.
Advantages of Shared Preferences
• It works on the key-value pair basis. Simply provide the key and get
corresponding value.
• Just a few lines of code required to manipulate data.
• Data is private to the corresponding application.
• It is useful to store user preferences.
• When needed, data can be shared among applications.
• Reading and writing data is easy and fast
•Unless the application is uninstalled or data is cleared from settings, data persists
in the application.

Disadvantages of Shared Preferences


• Cannot store a large amount of data.
• Cannot store Image, Audio or video data.
• Fails to store structured data.
• Storing huge amount of data in memory affects the speed and
efficiency of the application.
3. Retrieving Shared Preferences

➢Accessing shared preferences, is done using the


getSharedPreferences() method.

String name = sp.getString("username","new_value_for_user");


4. preference
framework and preference activity
➢Android offers an XML driven framework to create system-style
preference for your applications.
➢By using this preferences, activities can be created that are consistent
with those used in both native and other third party applications.
➢The preference framework consists of four parts :
a) Preference Screen Layout
b) Preference Activity and Preference Fragment
c) Preference Header Definition
d) Shared Preference Change Listener.
a). Defining a Preference Screen Layout
➢“Building user interface”, Preference Screen layout use a specialized
set of controls for Preference.
➢Each preference layout is defined as a hierarchy, beginning with a
single PreferenceScreen element:
<PreferenceScreen
xmlns:android=“http://schemas.android.com/apk/res/android”
</PreferenceScreen>
➢Within each preference screen you can include any combination of
PreferenceCategory and Preference<control> elements.
<PreferenceCategory
android:title=“My Preference Category” />
➢Android:key – The shared preference key
against which the selected value will be
recorded.
➢Android:title – The text displayed to
represent the preference.
➢Android:summary – The longer text
description displayed in a smaller font below
the title text.
➢Android:defaultValue – The default value
that will be displayed (and selected) if no
preference value has been assigned to the
associated preference key
➢.
➢Example :-
<PreferenceScreen>
<PreferenceCategory
android:title=“My Preference Category”>
<CheckBoxPreference
android:key=“PREF_CHECK_BOX”
android:title=“check box Preference”
android:summary=“checkbox Preference description”
android:defaultValue=“true”
/>
</PreferenceCategory>
</PreferenceScreen>
Native Preference Control

➢Android includes several preference control to build your preference


screen.
❖CheckBoxPreference – A standard preference checkbox controls
used to set preference to true or false. It is not mutually exclusive.
Multiple values can be selected using checkbox.
❖ EditTextPreference – It allows users to enter a string value as a
preference. Selecting the preference text at run time will display a
text entry dialog.
❖ListPreference – The preference equivalent of a spinner.
Selecting this preference will display a dialog box containing a list
of values from which to select. Different arrays can be specified to
contain the display text and selection values.
❖MultiSelectListPreference – Introduced in android 3.0 (API
level 11), this is the preference equvalent of a checkbox list.
Multiple values can be selected from list.
❖RingTonePreference – A specialized list preference that
presents the list of available ringtones for use selection. This is
particularly useful when you are constructing a screen to configure
notification settings.
➢Alternatively specialized preference control can be created by
extending the preference class
b). Introducing the Preference Fragment
➢Since android 3.0, the PreferenceFragment class has been used to
host the preference screens defined by Preference screen resources.
➢To Create the new Preference Fragment, extend the
PreferenceFragement Class.
Public class MyPreferenceFragement extends PreferenceFragement
➢To inflate the preference, override the onCreate handler and call
addPreferenceFromResource(), as shown here :
@override
Public void onCreate(Bundle savedinstancestate)
{
Super.onCreate(Bundle savedinstancestate);
addPreferenceFromResource(R.xml.userpreference);
}
➢Your application can include several different Preference Fragment,
which will be grouped according to the Preference.
c). Defining the Preference
Fragment Hierarchy Using Preference Header
➢Preference headers are XML resources that describes how the
preference fragment should be grouped and displayed within a
Preference Activity.
➢Preference headers are XML resources stored in the res/xml folder of
your project hierarchy.
➢The resource ID for each header is the filename (without extension).
➢Each header must be associated with a particular preference fragment
that will be displayed when its header is selected.
<Preference-header>
<header
android:fragment=“com.preference.MyPreferenceFragment”
android.icon=“@drawable/Preference_icon”
android:title=“My Preference”
android:summary=“description of these Preferences ”/>
</Preference-header>
d). Introducing the Preference Activity

➢The Preference activity class is used to host the preference fragment


hierarchy defined by a preference header resources.
➢Prior to android 3.0, the preference activity was used to host
preference screen directly.
➢To create a new preference activity, extend the PreferenceActivity
class as follows :
Public class FragmentPreferenceActivity extends PreferenceActivity
Preference screen can be inflated directly in the same way as you would
from a preference fragment – overriding the onCreate handler and
calling addPreferenceFromResource.
@override
Public void onCreate(Bundle savedinstancestate)
{
Super.onCreate(savedinstancestate);
addPreferenceFromResource(R.xml.userpreferenceheader);
}

➢Like all Activities, the preference Activity must included in the


application manifest.
<Activity
android:name=“.MyPreferenceActivity”
android:label=“My Preference”>
</Activity>
e). Introducing On shared Preference Change Listener
➢The onSharedPreferenceChangeListener can be implemented to
invoke a callback whenever a particular shared preference value is
added, removed or modified.
➢Using this handler, your application components can listen for
changes to user preference and update their UIs or behavior, as required.
➢Register your on shared preference change listener using the shared
preference you want to monitor.
➢Example :-
Public class MyActivity extends Activity implements
onSharedPreferenceChangeListener
{
@override
5. Persisting the
Application Instance State
➢To save Activity instance variable, android offers two specialized
variations of shared preference.
➢The first uses a shared preference named specifically for your
activity, whereas the other relies on series of life cycle event handlers.
Saving Activity state using shared Preference
➢To save activity information that doesn’t need to be shared with other
components, call Activity.getPreference() without specifying a shared
preference name.
➢This returns a shared preference using the calling activity’s class
names as the shared preference name.
SharedPreferences sp=getPreferences(Activity.MODE_PRIVATE);
SharedPreference.Editor Ed= sp.edit();
TextView txt=(TextView)findViewById(R.id.txt);
Ed.putString(“currentTextvalue”, txt.getText().toString());
Ed.apply();
Saving and Restoring Activity
instance state using the LifeCycle Handlers
➢Activities offer onSaveInstanceState handler to persist data
associated with UI state across sessions.
➢To save and restore the state of preference class implement the life
class methods such as onCreate or onRestoreInstanceState ,when the
activity is next created.
➢The data that should persist across user session should be stored using
shared Preference.
➢By overriding an activity’s onSaveInstanceState event handler, its
Bundle parameter can be used to save UI instance values.
6. Including Static Files as Resources
➢If application requires external file resources, it can be included them
in the package by placing them in the res/raw folder of project
hierarchy.
➢To access these read-only file resources, call the openRawResource
Resource res = getResources();
InputStream myfile= res.openRawResource(R.raw.myfilename);
➢Adding new files to your resources hierarchy is an excellent
alternative for large, pre existing data sources (such as dictionaries) for
which it’s not desirable to convert them into android database.
➢Android’s resource mechanism lets you specify alternative resource
files for different languages, locations and hardware configurations.
7. Working with File System

File Management tools


➢Android supplies some basic file management tools to help you deal
with the file system.
➢Many of these utilities are located within the java.io.File package.
➢Android does supply some specialized utilities for file management
that are available from the application context.
❖ deleteFile – enable you to remove files created by the current
application.
❖ fileList – returns a string array that includes all the files created
by the current application.
➢Many applications will create or download large files that are specific
to the application.
➢There are two options for storing these applications specific files:
❖ Internally
❖ Externally
a). Internal storage

➢By internal storage files can be saved directly on the device's internal
memory.
➢By default, files saved to the internal storage are accessible to their
application, other applications can not access them.
➢When the user uninstalls the application, these files are removed.
➢To create and save a private file to the internal storage:
❖Call openFileOutput () with the file name and the operating
mode. This returns a FileOutputStream.
❖Write on file with the write ().
❖Close the stream with close ().
When the data is larger in amount or the data type is not primitive, the data is stored in
the device storage.
Internal storage is a built-in-non-volatile memory which is always available on the
device.
• The internal storage directory is private to the application and the data cannot be
accessed by other applications.
• Moreover, text and binary data like images can be stored in device's internal
memory.
• The data saved in the internal storage of the device is removed as soon as the
application is uninstalled from the device.
• File class and its various methods are used to store and retrieve the data in internal
file storage.
• Advantages of internal file storage
• Data access is private to the application.
• Internal storage is always available on the device.
• Disadvantages of internal file storage
• Uninstalling the application removes data internal storage.
• Internal storage cannot store a large amount of data.

String FILENAME = "hello_file";


String str = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME,

Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
b). External storage

➢Each Android-compatible device supports an "external memory"


shared that can be used to save large files with any data type.
➢This may be removable storage media (such as an SD card) or an
internal memory (not removable).
➢Files saved to the external storage is accessible by all and can be
modified by the user when they allow USB mass storage to transfer files
from a computer.
➢Before doing any work with the external storage, you should always
call Environment.getExternalStorageState() to check that the media is
available.
➢The media can be mounted to a computer in read-only, or in some
other state.
➢User permissions is needed to access(read and write) external storage.
Any application or user can see and manipulate the data in external
storage.
Large size images, Audio and video files, downloads from the internet, Document
files etc. can be stored in external storage.
• Do not save private data in external storage.
Advantages of external file storage.
• Store huge amount of data.
• Can store any type of data.
•Data in external file storage remains in the storage even if the application is
uninstalled or data is cleared from settings.
Disadvantages of external file storage
• Data is world readable. In general, any application or user can read the data.
• Data is not always available as the user may remove the SD card from the device.
Module – 5
SQLite Database
1). Introducing Android Database
➢SQLite databases can be used to store application data using a
managed, structured approach.
➢Android offers a full SQLite relational database library.
➢Every application can create its own databases over which it has
complete control.
➢All these databases are private, accessible only by the application that
created them.
➢It has been implemented as a compact C library that’s include as part
of the android software stack.
➢SQLite is a well regarded relational database management system
(RDBMS). It is :
❖ Open Source
❖ Standards Compliant
❖ Light Weight
❖ Single tier
• SQLITE is server less.
• SQLITE offers a few data types.
• SQLITE uses cross platform database files.
• SQLITE stores data in one database files.
• SQLite does not have a storage class set aside for storing dates
and/or times. Instead, the built-in Date And Time Functions of
SQLite are capable of storing dates and times as TEXT,
REAL, or INTEGER values:

• BLOB stands for a binary large object that is a collection of


binary data stored as a value in the database. By using the
BLOB, you can store the documents, images, and other
multimedia files in the database
Content Values and Cursor

➢Content values are used to insert new rows into tables.


➢Each ContentValue objects represents a single table row as a map of
column names to values.
➢Database queries are returned as Cursor objects.
➢Rather than extracting and returning a copy of the result values,
cursor are pointer to the result set within the underlying data.
➢Cursor provide a managed way of controlling your position (row) in
the result set of a database query.
➢The Cursor class includes a number of navigation functions, including
, but not limited to, the following:

➢MoveToFirst : Move the cursor to the first row in the query


result.
➢MoveToNext : Move the cursor to the next row.
➢MoveToPrevious : Move the cursor to the Previous row.
➢getCount : Returns the number of rows in the result set.
➢getColumnName : Returns the name of the specified column
index.
➢ getColumnNames : Returns a string array of all the column names
in the current cursor.
➢MoveToPosition : Move the cursor to the specifies row
➢getPosition : Returns the current cursor position.
➢Android provides a convenient mechanism to ensure queries are
performed asynchronously.
➢The CursorLoader class and associated loader manager are introduced
in android 3.0.
3). Introducing the SQLiteOpenHelper
➢SQLiteOpenHelper is an abstract class used to implement the best
practice pattern for creating, opening and upgrading database.
➢Implementing an SQLite Open Helper :

Private static class DBOpenHelper extends SQLiteOpenHelper


{
//code
}

➢To access the database using the SQLite Open Helper, call
getWritableDatabase or getReadableDatabase to open and obtain a
writable or read-only instance of the underlying database, respectively.
4). Opening and Creating
Database without the SQLiteOpenHelper
➢In order to manage creation, opening and version control of
databases directly, openOrCreateDatabase method is used to create
the database itself :

SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
context.MODE_PRIVATE, null);

Database – Package - The main package in database is


android.database.sqlite that contains the classes to manage databases

Database – Creation - In order to create a database call the method


openOrCreateDatabase with database name and mode as a
parameter.
• Two methods can be used to implement insert, delete, read, update
operations.

• Using raw query method - These are simple SQL queries similar to other
databases like MySql, Sql Server etc . In this case user will have to write
query as text and passed the query string in
• rawQuery(String sql ,String [] selectionArgs) or
• execSQL(String sql,Object [] bindArgs) method to perform operations.
mydatabase.execSQL("INSERT INTO testtable
values(‘admin','admin');");

• Using parameterized queries - These are the queries which are


performed using inbuilt functions to insert, read, delete or update data.
These operation related functions are provided in SQLiteDatabase class.
8). Adding, Updating, and Removing Rows
➢The SQLiteDatabase class exposes insert, delete, and update methods
that encapsulate the SQL statements required to perform these actions.
➢Additionally, the execSQL method lets you execute any valid SQL
statement on your database tables.
Inserting Rows
➢To create a new row, construct a ContentValues object and use its put
methods to add name/value pairs representing each column name and
its associated value.
➢Insert the new row by passing the Content Values into the insert
method called on the target database — along with the table name.
➢ To perform insert operation using parameterize query call insert
function available in SQLiteDatabase class. The insert() function
has three parameters
To insert an item
public long insert(String tableName, String nullColumnHack, ContentValues
values)
tableName is name of table in which data to be inserted.
NullColumnHack may be passed null.
ContentValues : values that needs to be inserted into the table.
public void addltem(Item item){
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues. put("name“,item.name);
contentValues.put("description“, item.description);
db.insert("Items", null, contentValues);
db.close();
}
Updating Rows
➢Updating rows is also done with Content Values.
➢Create a new ContentValues object, using the put methods to assign
new values to each column you want to update.
➢Call the update method on the database, passing in the table name, the
updated Content Values object, and a where clause that specifies the
row(s) to update.
// Create the updated row Content Values.
ContentValues updatedValues = new ContentValues();
public void updateltem(Item item)
{
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("id’’•
, item. id);
contentValues.put("name’’, item.name);
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.update("Items"•
, contentValues, whereClause, whereArgs);
}
Deleting Rows

➢To delete a row, simply call the delete method on a database, specifying
the table name and a where clause that returns the rows you want to
delete.
➢Delete function is available in SQLiteDatabase class.
➢public int delete(String tableName, String whereClause, String []
whereArgs)
➢Here whereClause is optional, passing null will delete all rows in
table.
➢Delete function will return number of affected row if whereClause
passed, otherwise will return 0.
To delete an Item
public void deleteltem(Item item)
{
SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items"•
, whereClause, whereArgs);
}
To replace rows in table –

SqliteDatabase db = getDatabase();
db.replace(tablename, null, contentValues);

To perform a query
SqliteDatabase db = getDatabase();
Cursor res = db.query(tablename, columnname, selectionclause,
selectionargs, groupby, having, orderby);
SQLITE AND DATABASE CENTRIC DATA MODEL FOR ANDROID

An architecture pattern gives modularity to the project. It makes the task easy for
developers to maintain the software and to expand the features of the application in the
future.
Model—View—Controller(MVC) Pattern is one of the architecture pattern in
Android.
The MVC pattern suggests splitting the code into 3 components. While creating the
class/file of the application, the developer must categorize it into one of the following
three layers:
Model: This component stores the application data. It has no knowledge about the
interface. The model is responsible for handling the domain logic(real-world business
rules) and communication with the database and network layers.
View: It is the UI(User Interface) layer that holds components
that are visible on the screen. Moreover, it provides the
visualization of the data stored in the Model and offers interaction
to the user.
Controller: This component establishes the relationship between
the View and the Model. It contains the core application logic
and gets informed of the user’s behaviour and updates the Model
as per the need.
Database - Helper class

For managing all the operations related to the database and for
version management, a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and
update of the database.

Syntax
public class DBHelper extends SQLiteOpenHelper {
public DBHelper()
{
super(context, DATABASE_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db){}
public void onUpgrgde(SQLiteDatabase database, int oldVersion,
int newVersion){}
Android Database Classes
Java classes that are responsible for providing access to the SQLite functions
-
1. SQLite Database: This is the Android's Java interface to its relational
database, SQLite. It also supports an SQL or Structured Query Language
implementation which is rich enough to handle any requirement for mobile
application.

2.Cursor: A cursor is a container which holds the results of a database query


and also supports the commonly used MVC design pattern. A cursor also has
the ability to represent multiple objects without creating instance for each and
every one.
The cursor returns the values depending upon the current position of the
cursor index.
3. SQLiteOpenHelper: The open helper provides a life cycle
framework to create and upgrade our application database.

4. SQLiteQueryBuilder: The query builder provides a high-level


abstraction to create SQLite queries to be used in Android
applications. The task of writing queries for the application can be
simplified and it also saves an enormous amount of time.

You might also like