0% found this document useful (0 votes)
5 views52 pages

Android Unit V

The document provides an overview of data persistence in Android programming, detailing various methods such as SharedPreferences, Internal Storage, External Storage, SQLite Databases, and Network connections. It discusses the advantages and disadvantages of each method, including what types of data are suitable for storage and how to implement these storage options. Additionally, it covers the Preference Framework for creating user-friendly settings screens within applications.

Uploaded by

abhinavinil311
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)
5 views52 pages

Android Unit V

The document provides an overview of data persistence in Android programming, detailing various methods such as SharedPreferences, Internal Storage, External Storage, SQLite Databases, and Network connections. It discusses the advantages and disadvantages of each method, including what types of data are suitable for storage and how to implement these storage options. Additionally, it covers the Preference Framework for creating user-friendly settings screens within applications.

Uploaded by

abhinavinil311
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

Android Programming

Unit V

Persisting data - Files, saving state and preferences - saving application data,
creating, saving and retrieving shared preferences, preference framework and
preference activity, preference layout in XML, native preference controls,
preference fragments, preference activity, persisting the application state,
including tatic files as resources, Working with file system, SQL Lite – SQL Lite
types, database manipulation using SQL Lite, SQL and database centric data
model for Android, Android database classes.
PERSISTING DATA
▪ Persistent data denotes information that is infrequently accessed and not likely to be
modified.
▪ Android provides several options for saving data persistent applications
▪ The solution that is chosen will depend on specific needs, such as whether the data should
be private to their application or accessible to other applications (and user) and how much
space data require.
▪ Data storage options in android are the following
o SharedPreferences: store primitive private data on key-value pairs.
o Internal Storage: store private data in the device memory. (With object persistence)
o External Storage: store public data on the shared external storage.
o SQLite Databases: store structured data in a private database.
o Network connection:-store data on the web with own network server
Saved Instance State

▪ Saved Instance state is the very first scene when you are storing and retrieving the data in
your application.
▪ onSaveInstaceState() method is called when an activity is destroyed which takes a Bundle as
a parameter
▪ This bundle is a collection of a key-value pair in which we can store the state of every view
in the bundle let it be Edittext, TextView, CheckBox or the scrolled position of list view or
recycler view.
▪ When the application is restarted then onRestoreInstanceState() is called to which we
provide this bundle and it automatically restores the activity to the state in which it was
closed. This agenda enhances the user experience
▪ what to save?
texts in edit texts, instances of ImageViews, the position of scroll views, the current
playback time of videos, checks of checkboxes, currently selected view
▪ what not to save?
Images, videos, files, Internet downloads
▪ Advantages of saved instance state
o State of the activity is restored if the activity is closed.
o saving data is quick and simple in key-value pairs.
o useful when device orientation is changed.
▪ Disadvantages of saved instance state
o Data stored is not persistent i.e; data is lost if the device is restarted.
o Do not save data if the app is closed via finish() method.
1. SHARED PREFERENCES
▪ Shared preferences provide a quick interface to save and retrieve small unstructured data in
a key-value pair.
▪ You have a string key, and the corresponding primitive value for that key: boolean, String,
int, float or long.
▪ The data in shared preferences persist across user session even if application is killed and
restarted or the device is rebooted.
▪ Android platform stores the applications 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).
▪ Shared preference data is lost when the user uninstalls the application or clears the
application data from settings.
What to save and what not?
▪ To point out what kind of data to store in shared preference consider the example of a game
application.
▪ 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.
▪ Also, the application has to maintain user settings preferences, if the user has turned on/off
the music of the game or notifications.
▪ At the same time, there are things that shared preferences are not capable of storing.
▪ 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 when you need to store Images, videos, Audio files, large
text files, spreadsheets or presentations.
Advantages of Shared Preferences
▪ Works on the key-value basis. Simply provide the key and get corresponding value.
▪ Just a few lines of code required to manipulate data.
▪ Data is private to your application
▪ Useful when need to store user preferences.
▪ When needed, you can share data 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.
2. Internal File storage
▪ When the data is larger in amount or the data type
is not primitive, we store the data in device storage.
▪ Every Android device’s file storage area is divided
into two parts: Internal storage and External storage.
▪ Internal storage is a built-in-non-volatile memory
which is always available on the device.
▪ The internal storage directory is private to your application and the data cannot be accessed
by other applications.
▪ Moreover, you may store text and binary data like images in your 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.
▪ what to save?
large text files, spreadsheets or CSV files, Image thumbnails
▪ What not to save?
Large audio files, video files, files larger than total 1mb.
▪ Advantages of internal file storage
o Data access is private
o neither the user nor other applications can access the data in internal storage.
o Internal storage is always available on the device.
o Read and write data do not require user permissions.
▪ Disadvantages of internal file storage
o Uninstalling the application removes data internal storage.
o cannot store a large amount of data.
3. External file storage
▪ External storage is a removable storage medium like an SD Card.
▪ Today a lot of devices do not support SD card.
▪ However, the permanent storage is divided into internal and
external storage modules.
▪ You will need user permissions to access(read and write) external
storage.
▪ The external storage is however by default public in access.
▪ Any application or user can see and manipulate the data in
external storage.
▪ File class and its methods to save, retrieve and delete the data in
external file storage.
▪ It stores a large amount of data with any data type.
▪ what to save?
Large size images, Audio and video files, downloads from the internet, Document files
▪ what not to save?
Any data that you do not want to share with other applications or the user.
▪ Advantages of external file storage
o Store huge amount of data.
o can store any type of data.
o data remains in the storage even if the application is uninstalled or data is cleared from
settings.
▪ Disadvantages of external file storage
o Data is world readable. In general, any application or user can read the data.
o Not always available as the user may remove the SD card from the device.
4. SQLite Database
▪ SQLite is an RDBMS library that implements SQL database engine which is:
o self-contained (no other component required)
o serverless (no server backend)
o zero-configuration (does not need to configure)
o transactional (changes within a single transaction in SQLite)
o stores data in a table of rows and columns.
▪ Transactions in SQLite are ACID and the system crashes do not affect them.
▪ SQLite database is a premium choice when you need to manipulate structured data
frequently.
▪ Query
• We use a query language to interact with the database. Queries can be complex but
basically, we use the following operations:
o inserting data
o deleting data
o updating data
o retrieving data
▪ Cursors
• A Cursor is an object interface that provides random read-write access to the result set
returned by the database query.
• In other words, A cursor is a pointer to the rows of the table of the database.
• A cursor class provides methods to run the cursor throughout the structured data, and
methods to retrieve data from columns of each row.
▪ what to save?
Related data like a phone contact, user statistics, update, delete and view flags, URLs and
URI
▪ what not to save?
Images as well as media files, non-relational data, single key-value pair, Document files
▪ Advantages of SQLite database
o Serverless hence, no configuration required
o able to control redundancy of data
o maintains the integrity of stored information
o can share data using content providers when needed
o integrated with Android studio
▪ Disadvantages of SQLite database
o Cannot store media files
o data loss on removal of the application
5. Network connection
▪ The network connection can be used to
retrieve and send data to a back-end server
of your application.
▪ In this case, backend server maintains the
database of your application.
▪ There are several APIs through which you can access this data. Every time you have to hit an
API URL to receive or send data.
▪ To perform network operations we have the following packages that we can use:
o [Link].*
o [Link].*
▪ Every time to perform a network operation you have to open an HTTP connection and
provide the method as GET or POST.
▪ After that, you may be able to connect to the API URL and exchange the data.
▪ what to save?
o Media files, Documents, User preferences
▪ what not to save?
o Application settings
o Any data that you may need offline
▪ Advantages of Network connection
o Even uninstalling the application do not affect the data.
o Can store any amount of data
▪ Disadvantages of network connection
o Internet connection is must to transfer data.
o If backend server crashes then all the data may lose.
SHARED PREFERENCE
▪ Shared Preferences is the way in which one can store and retrieve small amounts of
primitive data as key/value pairs to a file on the device storage such as String, int, float,
Boolean that make up your preferences in an XML file inside the app on the device storage.
▪ Shared Preferences can be thought of as a dictionary or a key/value pair.
▪ For example, you might have a key being “username” and for the value, you might store the
user’s username. And then you could retrieve that by its key (here username)
▪ Shared Preferences class provides APIs for reading, writing and managing this data.
▪ In order to use shared preferences ,call a method getSharedPreferences() that returns a
shared preference instance pointing to the file that contains the value of preferences
Syntax:
o public abstract SharedPreferences getSharedPreferences(String name, int mode)
o SharedPreferences sharedPreferences = getSharedPreferences(MyPreferences,
MODE_PRIVATE);
▪ This method takes two arguments, first being the name of the SharedPreference(SP) file and
other is the context mode that we want to store our file in.
o MODE_PUBLIC will make the file public which could be accessible by other applications in
the device
o MODE_PRIVATE keeps the files private and secure user’s data.
o MODE_APPEND is used while reading the data from SP file.

Nested classes of Shared Preferences


▪ [Link]: Interface used to write(edit) data in SP file. Once editing has been
done, one must commit() or apply() the changes made to the file.
▪ [Link](): Called when a shared preference
is changed, added, or removed. This may be called even if a preference is set to its existing
value. This callback will be run on your main thread
▪ To Write Data in Shared Preferences use [Link]
Syntax:
[Link] = [Link]();
[Link](keyString, valueString);
[Link]();

▪ To read data use shared preference methods such as


o getAll(): This method is used to retrieve all values from the preferences.
o getBoolean(String key, booleandefValue): This method is used to retrieve a Boolean
value from the preferences.
o getFloat(String key, float defValue): This method is used to retrieve a float value from
the preferences.
o getInt(String key, int defValue): This method is used to retrieve an int value from the
preferences.
o getLong(String key, long defValue): This method is used to retrieve a long value from the
preferences.
o getString(String key, String defValue): This method is used to retrieve a String value
from the preferences.
o getStringSet(String key, Set defValues): This method is used to retrieve a set of String
values from the preferences.

How to Write Data in Shared Preferences


// Storing data into SharedPreferences
SharedPreferencessharedPreferences=getSharedPreferences("MySharedPref“,MODE_PRIVATE);
// Creating an Editor object
// to edit(write to the file)
[Link]= [Link]();
// Storing the key and its value
// as the data fetched from edittext
[Link]( "name", [Link]().toString());
[Link]( "age", [Link]( [Link]().toString()));
// Once the changes have been made,
// we need to commit to apply those changes made,
// otherwise, it will throw an error
[Link]();

How to Read Data in Shared Preferences


// Retrieving the value using its keys
// the file name must be same in both saving
// and retrieving the data
SharedPreferencessh= getSharedPreferences("MySharedPref",MODE_APPEND);
// The value will be default as empty string because for the very first time when the app is opened,
there is nothing to show
String s1 = [Link]("name", "");
Int a = [Link]("age", 0);
// We can then use the data
[Link](s1);
[Link]([Link](a));

THE PREFERENCE FRAMEWORK AND THE PREFERENCE ACTIVITY


▪ Android offers an XML-driven framework to create system-style Preference Screens for your
applications.
▪ By using this framework you can create Preference Activities that are consistent with those
used in both native and other third-party applications.
▪ This has two distinct advantages:
o Users will be familiar with the layout and use of your settings screens.
o You can integrate settings screens from other applications (including system settings such
as location settings) into your application’s preferences.
▪ The preference framework consists of four parts:
o Preference Screen layout —An XML file that defines the hierarchy of items displayed in
your Preference screens. It specifies the text and associated controls to display, the
allowed values, and the Shared Preference keys to use for each control.
o Preference Activity and Preference Fragment —Extensions of PreferenceActivity and
PreferenceFragment respectively, that are used to host the Preference Screens. Prior to
Android 3.0, Preference Activities hosted the Preference Screen directly; since then,
Preference Screens are hosted by Preference Fragments, which, in turn, are hosted by
Preference Activities.
o Preference Header definition —An XML file that defines the Preference Fragments for
your application and the hierarchy that should be used to display them.
o Shared Preference Change Listener —An implementation of the
OnSharedPreferenceChangeListener class used to listen for changes to Shared
Preferences.
Defining a Preference Screen Layout in XML
▪ Unlike in the standard UI layout, preference definitions are stored in the res/xml resources
folder.
▪ Although conceptually they are similar to the UI layout resources
▪ Preference Screen layouts use a specialized set of controls designed specifically for
preferences.
▪ Each preference layout is defined as a hierarchy, beginning with a single
PreferenceScreenelement:
<?xml version=”1.0” encoding=”utf-8”?>
<PreferenceScreenxmlns:android=”[Link]
</PreferenceScreen>
▪ Additional Preference Screen elements, each of which will be represented as a selectable
element that will display a new screen when clicked.
▪ Within each Preference Screen you can include any
combination of PreferenceCategory and Preference
<control> elements.
▪ Preference Category elements, are used to break each
Preference Screen into subcategories using a title bar
separator:
<PreferenceCategory android:title=”My Preference Category”/>
SIM card lock, device administration, and credential
storage Preference Categories used on the Security
Preference Screen

Attributes of preference control


▪ 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

Native Preference Control


▪ CheckBoxPreference—A standard preference check box control used to set preferences to
true or false.
▪ EditTextPreference—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. You can specify different
arrays to contain the display text and selection values.
▪ MultiSelectListPreference—Introduced in Android 3.0 (API level 11), this is the preference
equivalent of a check box list.
▪ RingtonePreference—A specialized List Preference that presents the list of available
ringtones for user selection. This is particularly useful when you’re constructing a screen to
configure notification settings.
▪ You can use each preference control to construct your Preference Screen hierarchy.
Alternatively, you can create your own specialized preference controls by extending the
Preference classes

A simple Shared Preferences screen


<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreenxmlns:android="[Link]
<PreferenceCategoryandroid:title="Basics">
<CheckBoxPreference
android:key="checkbox"
android:summary="Tap to check if on or off"
android:title="Checkbox Preference"/>
<RingtonePreference
android:key="ringtone"
android:showDefault="true"
android:showSilent="true"
android:summary="Pick a ringtone you like"
android:title="Ringtone Preference" />
</PreferenceCategory>
</PreferenceScreen>

Preference Fragment
▪ Since Android 3.0, the PreferenceFragment class has been used to host the preference
screens defined by Preferences Screen resources.
▪ To create a new Preference Fragment, extend the PreferenceFragment class, as follows:
public class MyPreferenceFragment extends PreferenceFragment
▪ To inflate the preferences, override the onCreatehandler and call
addPreferencesFromResource, as shown here:
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
//Load the preferences from an XML resource
addPreferencesFromResource([Link]);
}
▪ Your application can include several different Preference Fragments, which will be grouped
according to the Preference Header hierarchy and displayed within a Preference Activity.
Preference Activity
▪ PreferenceActivity class is used to host the Preference Fragment hierarchy defined by a
preferenceheaders resource
▪ To display settings in an activity extend the preferenceActivity class
▪ This is an extension of traditional activity class that displays a list of settings based on a
hierarchy of Preference objects
▪ To create a new Preference Activity, extend the PreferenceActivity class as follows:
public class MyFragmentPreferenceActivity extends PreferenceActivity

▪ Inflate the Preference Screen directly in the same way as you would from a Preference
Fragment —
o by overriding the onCreatehandler and calling add PreferencesFromResource, specifying
the Preference Screen layout XML resource to display within that Activity:
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
addPreferencesFromResource([Link]); }
▪ Like all Activities, the Preference Activity must be included in the application manifest:
<activity android:name=“MyPreferenceActivity”
android:label=“My Preferences”> </activity>
▪ To display the application settings hosted in this Activity, open it by calling startActivity or
startActivityForResult:
Intent i= new Intent(this, [Link]);
startActivityForResult(i, SHOW_PREFERENCES);
INCLUDING STATIC FILES AS RESOURCES
▪ If your application requires external file resources, you can include them in your distribution
package by placing them in the res/raw folder of your project hierarchy.
▪ To access these read-only file resources, call the openRawResource method from your
application’s Resource object to receive an InputStream based on the specified file.
▪ Pass in the filename (without the extension) as the variable name from the [Link], as shown
in the following skeleton code:
▪ Resources myResources= getResources();
▪ InputStreammyFile= [Link]([Link]);
▪ Adding raw files to your resources hierarchy is an excellent alternative for large, preexisting data
sources (such as dictionaries) for which it’s not desirable (or even possible) to convert them into
Android databases.
▪ Android’s resource mechanism lets you specify alternative resource files for different languages,
locations, and hardware configurations.
▪ For example, you could create an application that loads a different dictionary resource based on
the user’s language settings.
WORKING WITH FILE SYSTEM

File-Management Tools:
▪ Android supplies some basic file-management tools to deal with the file system.
▪ Many of these utilities are located within the [Link].
▪ Android supply some specialized utilities for file management that are available from the
application Context.
o deleteFile—Enables you to remove files created by the current application
o fileList—Returns a string array that includes all the files created by the current
application
▪ These methods are particularly useful for cleaning up temporary files left behind if your
application crashes or is killed unexpectedly.
Using Application-Specific Folders to Store Files
▪ Many applications will create or download files that are specific to the application.
▪ There are two options for storing these application-specific files: internally or externally.
▪ Android offers two corresponding methods via the application Context, getDirand
getExternalFilesDir, both of which return a File object that contains the path to the internal
and external application file storage directory, respectively.
▪ Files stored in the application folders should be specific to the parent application and are
typically not detected by the media-scanner, and therefore won’t be added to the Media
Library automatically.

Creating Private Application Files


▪ Android offers the openFileInput and openFileOutput methods to simplify reading and
writing streams from and to files stored in the application’s sandbox.
▪ String FILE_NAME = “[Link]”;
// Create a new output file stream that’s private to this application.
▪ FileOutputStream fos= openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
// Create a new file input stream.
▪ FileInputStream fis= openFileInput(FILE_NAME);
▪ By default, files created using the openFileOutput method are private to the calling
application —a different application will be denied access.

Creating Public Application Files


▪ The standard way to share a file between applications is to use a Content Provider.
▪ Alternatively, you can specify either Context.MODE_WORLD_READABLE or
Context.MODE_WORLD_WRITEABLE when creating the output file, to make it available in
other applications
▪ String OUTPUT_FILE = “[Link]”;
▪ FileOutputStreamfos= openFileOutput(OUTPUT_FILE,Context.MODE_WORLD_WRITEABLE);
INTRODUCING ANDROID DATABASES
▪ Android provides structured data persistence through a combination of SQLite databases and
Content Providers.
▪ 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
▪ Having created your underlying data store, Content Providers offer a generic, well-defined
interface for using and sharing data that provides a consistent abstraction from the
underlying data source.

SQLite
▪ SQLite is a well-regarded relational database management system (RDBMS).
▪ It is:
o Open-source
o Standards-compliant
o Lightweight
o Single-tier
▪ It has been implemented as a compact C library that’s included as part of the Android
software stack
▪ By being implemented as a library, rather than running as a separate ongoing process, each
SQLite database is an integrated part of the application that created it.
▪ This reduces external dependencies, minimizes latency, and simplifies transaction locking
and synchronization.
▪ SQLite is a opensource SQL database that stores data to a text file on a device.
▪ Android comes in with built in SQLite database implementation.
▪ SQLite supports all the relational database features. In order to access this database, you
don't need to establish any kind of connections for it like JDBC,ODBC e.t.c
SQLite is not like any other database
▪ Though SQLite offers quite an impressive feature set given its size, it differs in many aspects
from a conventional database system:
o SQLite is serverless
o SQLite stores data in one database file
o SQLite offers only a few data types
o SQLite uses manifest typing instead of static types
o SQLite has no fixed column length
o SQLite uses cross-platform database files

SQLite data types


▪ SQLite offers fewer datatypes
▪ If you use other types (like varchar) in your CREATE TABLE statement SQLite maps them as
closely as possible to any of these types.
▪ Most SQL database uses static, rigid typing. With static typing, the datatype of a value is
determined by its container -the particular column in which the value is stored.
▪ SQLite uses a more general dynamic type system.
▪ In SQLite, the datatype of a value is associated with the value itself, not with its container.
▪ SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as
integers 0 (false) and 1 (true).
▪ 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

Database manipulation using SQLLite


▪ Database -Package
o The main package is [Link] that contains the classes to manage your
own databases
▪ Database -Creation
o In order to create a database you just need to call this method openOrCreateDatabase
with your database name and mode as a parameter.
o It returns an instance of SQLite database which you have to receive in your own object.
o Syntax:
SQLiteDatabasemydatabase= openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
▪ Table creation
[Link]("CREATE TABLE IF NOT EXISTS testtable(Username text, Password
text ) ;");

Database manipulation
▪ To perform insert, read, delete, update operation there are two different ways:
▪ Write parameterized queries (Recommended)
▪ Write raw queries
▪ Parameterized Queries: These are those queries which are performed using inbuilt functions
to insert, read, delete or update data. These operation related functions are provided in
SQLiteDatabase class.
▪ Raw Queries: These are simple sql queries similar to other databases like MySql, SqlServer
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.
▪ Example of raw query to insert data:
[Link]("INSERT INTO testtableVALUES('admin','admin');");
▪ To perform insert operation using parameterize query
o call insert function available in SQLiteDatabaseclass
o insert() function has three parameters like public long insert(String
tableName,StringnullColumnHack,ContentValuesvalues)
o where tableName is name of table in which data to be inserted.
o NullColumnHack may be passed null, it require table column value in case we don’t put
column name in ContentValues object so a null value must be inserted for that particular
column
o ContentValues: values that needs to be inserted into the table
public void addItem(Item item) {
SQLiteDatabasedb= getWritableDatabase();
ContentValuescontentValues= new ContentValues();
[Link]("name",[Link]);
// name -column
[Link]("description",[Link]);
// description is column in items table, [Link] value for description
[Link]("Items", null, contentValues);//Items is table name
[Link]();
}
UPDATE
▪ Example of raw query
String updateQuery="UPDATE myTable SET salary = 5000 WHERE id=5”;
[Link](updateQuery, null);
▪ Parameterized query
o Update function is available in SQLiteDatabaseclass
o public int update(String tableName, ContentValuescontentValues, StringwhereClause,
String[] whereArgs)
o whereClause tells the database where to update data in table, it’s recommended to pass
?s (questions) along with column name in whereClause String.
o Similarly whereArgs array will contain values for those columns against ?s
o Update function will return number of rows affected if success, 0 otherwise.
UPDATE
public void updateItem(Item item) {
SQLiteDatabase db= getWritableDatabase();
ContentValues contentValues= new ContentValues();
[Link]("id", [Link]);
[Link]("name", [Link]);
[Link]("description", [Link]);
String whereClause= "id=?";
String whereArgs[] = {[Link]()};
[Link]("Items", contentValues, whereClause, whereArgs);
}
DELETE
▪ Example of raw query
String deleteQuery=“DELETE myTableWHERE id=5”;
[Link](deleteQuery, null);
▪ Parameterized query
o Delete function is available in SQLiteDatabaseclass
o public int delete(String tableName, StringwhereClause, String[] whereArgs)
o Here whereClause is optional, passing null will delete all rows in table.
o Delete function will return number of affected row if whereClause passed otherwise will
return 0.
o If you want to remove all rows and require count of deleted ones also then pass 1 as
whereClause.
DELETE
▪ Parameterized query
public void deleteItem(Item item) {
SQLiteDatabase db= getWritableDatabase();
String whereClause= "id=?";
String whereArgs[] = {[Link]()};
[Link]("Items", whereClause, whereArgs);
}
DATABASE – Fetching
▪ We can retrieve anything from database using an object of the Cursor class.
▪ We will call a method of this class called rawQuery and it will return a resultset with the
cursor pointing to the table.
▪ We can move the cursor forward and retrieve the data.
Cursor resultSet = [Link](“Select * from testable”, null);
[Link]();
String username = [Link](0);
String password = [Link](1);
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 DBHelperextends SQLiteOpenHelper{
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabasedb) {}
public void onUpgrade(SQLiteDatabasedatabase, int oldVersion, int newVersion) {}
}
Android Database Classes
▪ Java classes which are responsible to provide 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:
o A cursor is a container which holds the results of a database query and also supports the
commonly used MVC design pattern.
o Cursors are very much similar to the JDBC result sets which returns the value of any
database query. A cursor also has the ability to represent multiple objects without
creating instance for each and every one.
o The cursor returns the values depending upon the current position of the cursor index,
which we can increase by calling the method [Link], or decrease by calling
[Link] as we need
3. SQLiteOpenHelper: The open helper provides a life cycle framework to create and
upgrade our application database. This class is used to provide assistance in the critical task
which transitions the data from one version of an application to a new set of database tables
in a newer version of same or another application.
4. SQLiteQueryBuilder: The query builder provides a high-level abstraction to create SQLite
queries to be used in Android applications. In fact we can simplify the task of writing queries
for our application and it also saves an enormous amount of time.

You might also like