Unit 4 (Questions)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Mobile Computing

Unit No-:04
Data Persistence in Android
1) What is Data Persistence? List out the ways to persist data in Android.
In general, there you can store data in only two ways. Either you have to save it locally on your
mobile device or keep it somewhere else, like on an SD card or cloud storage. So, we can say
data persistence in Android is of two types. The first one is, On-device and the Second, Off
device.
Besides that, functionality-wise, there are three main categories for data persistence and five
categories by sub-categories. So you will see here five categories, and for today we will sort this
article into 3 categories.

Five Different Types of Persistent Data in an Android Application


Here we will show you the different persistent data types of all methods available for storing
Android application data.
1. Data Storage / File IO
2. Shared preference
3. SQLite Database
4. Custom Content Provider
5. Web Services / Cloud Storage

Let me show you in detail the description.


Data Storage:
Data storage or File IO is more like internal storage for data persistence. In general, This one is
easier than others where you can store any data like image, XML, JSON, etc.
Then, as needed, you can keep all the data using this method on your file system. Later you will
have an idea of performing this kind of method for your Android device.

Shared Preference:
Shared preference is the kind of data persistence where you can only store XML files to store
user data. Like, User id, password, email, or something like that.
Shared Preference can not store media files.
SQLite Database:
SQLite is an embedded type of software where you can write SQL queries to store or manage
data. Of course, you can use SQLite or any kind of MDBMS to store data. But, Using SQLite is
beneficial because it is lightweight and easy to use on every device.

Custom Content Provider:


This one is related to the SQLite database. You can get data from a database or place data in a
database. Therefore, you will see a custom content provider in the SQL database.
Web Services:
You will see this as an off-device where you save files online. This one also refers to a memory
card or sd card as a cloud device.
Below you will see these methods sorted according to their similarities, expressed in three
ways. Here you will learn those three methods and implementation also.

2) Write short note on –


a) SQLite

SQLite is an open-source relational database i.e. used to perform database operations on


android devices such as storing, manipulating or retrieving persistent data from the database.

It is embedded in android bydefault. So, there is no need to perform any database setup or
administration task.Here, we are going to see the example of sqlite to store and fetch the data.
Data is displayed in the logcat. For displaying data on the spinner or listview, move to the next
page.

SQLiteOpenHelper class provides the functionality to use the SQLite database.

b) SQLiteOpenHelper
The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version
management. For performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version) opening and managing the
database.

SQLiteOpenHelper(Context context, String name, creates an object for creating,


SQLiteDatabase.CursorFactory factory, int version, opening and managing the
DatabaseErrorHandler errorHandler) database. It specifies the error
handler.
Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

public abstract void onCreate(SQLiteDatabase db) called only once when database is
created for the first time.

public abstract void onUpgrade(SQLiteDatabase db, int called when database needs to be
oldVersion, int newVersion) upgraded.

public synchronized void close () closes the database object.

c) SQLiteDatabase
Android SQLite is a very lightweight database which comes with Android OS. Android SQLite
combines a clean SQL interface with a very small memory footprint and decent speed. For
Android, SQLite is “baked into” the Android runtime, so every Android application can create
its own SQLite databases. Android SQLite native API is not JDBC, as JDBC might be too
much overhead for a memory-limited smartphone. Once a database is created successfully its
located in data/data//databases/ accessible from Android Device Monitor. SQLite is a
typical relational database, containing tables (which consists of rows and columns), indexes
etc. We can create our own tables to hold the data accordingly. This structure is referred to as
a schema.

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String inserts a record on the database. The table specifies the
nullColumnHack, ContentValues table name, nullColumnHack doesn't allow
values) completely null values. If second argument is null,
android will store null values if values are empty. The
third argument specifies the values to be stored.

int update(String table, updates a row.


ContentValues values, String
whereClause, String[] whereArgs)
Cursor query(String table, String[] returns a cursor over the resultset.
columns, String selection, String[]
selectionArgs, String groupBy,
String having, String orderBy)

3) How to create a database in Android? Explain the steps involved in


performing Database Operations.
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter. It returns an instance of SQLite database which you
have to receive in your own object.Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Apart from this , there are other functions available in the database package , that does this job.
They are listed below

Sr.No Method & Description

1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,


DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The
common flags mode could be OPEN_READWRITE OPEN_READONLY

2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)


It is similar to the above method as it also opens the existing database but it does not
define any handler to handle the errors of databases

3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)


It not only opens but create the database if it not exists. This method is equivalent to
openDatabase method.

4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)


This method is similar to above method but it takes the File object as a path rather then
a string. It is equivalent to file.getPath()
4) How to create a database in Android? Explain the steps involved in
inserting a record with example.
we can create table or insert data into table using execSQL method defined in SQLiteDatabase
class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the
same job but take some additional parameter is given below

Sr.No Method & Description

1 execSQL(String sql, Object[] bindArgs)


This method not only insert data , but also used to update or modify already existing
data in database using bind arguments

To perform insert operation using parameterized query we have to call insert function available
in SQLiteDatabase class. insert() function has three parameters like public long insert(String
tableName,String nullColumnHack,ContentValues values) where tableName is name of table in
which data to be inserted.

public long insert(String tableName,String nullColumnHack,ContentValues values)

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, values
are those values that needs to be inserted- ContentValues is a key-pair based object which accepts
all primitive type values so whenever data is being put in ContentValues object it should be put
again table column name as key and data as value. insert function will return a long value i.e
number of inserted row if successfully inserted, – 1 otherwise.
Here is simple example:

//Item is a class representing any item with id, name and description.
public void addItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name",item.name);
// name - column
contentValues.put("description",item.description);
// description is column in items table, item.description has value for description
db.insert("Items", null, contentValues);//Items is table name
db.close();
}

5) How to create a database in Android? Explain the steps involved in


updating a record with example.
Update function is quite similar to insert but it requires two additional parameters, it doesn’t
required nullColumnHack. It has total four parameters two are similar to insert function that is
tableName and contentValues. Another two are whereClause(String) and whereArgs(String[]).
Update function is available in SQLiteDatabase class it looks as follows:

public int update(String tableName,ContentValues contentValues,String whereClause,String[] w


hereArgs)

Here whereClause is tell the database where to update data in table, it’s recommended to pass ?s
(questions) along with column name in whereClause String. Similarly whereArgs array will
contain values for those columns whose against ?s has been put in whereClause. Update function
will return number of rows affected if success, 0 otherwise.
Here is simple use of update:

//Item is a class representing any item with id, name and description
public void updateItem(Item item) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("id", item.id);
contentValues.put("name", item.name);
contentValues.put("description", item.description);
String whereClause = "id=?";String whereArgs[] = {item.id.toString()};

db.update("Items", contentValues, whereClause, whereArgs);}


6) How to create a database in Android? Explain the steps involved in deleting
a record with example.
Similar to insert and update, delete function is available in SQLiteDatabase class, So delete is
very similar to update function apart from ContentValues object as it’s not required in delete.
public int delete(String tableName,String whereClause,String [] whereArgs) function has three
parameters these are totally similar to update function’s parameters and are used in same way as
in update function.
Here is simple use of delete:

public void deleteItem(Item item) {


SQLiteDatabase db = getWritableDatabase();
String whereClause = "id=?";
String whereArgs[] = {item.id.toString()};
db.delete("Items", whereClause, whereArgs);
}

7) What is Content Provider? How to access data using Content Provider?


A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class. A content provider can use
different ways to store its data and the data can be stored in a database, in files, or even over a
network.

sometimes it is required to share data across applications. This is where content providers
become very useful.

Content providers let you centralize content in one place and have many different applications
access it as needed. A content provider behaves very much like a database where you can query
it, edit its content, as well as add or delete content using insert(), update(), delete(), and query()
methods. In most cases this data is stored in an SQlite database.
A content provider is implemented as a subclass of ContentProvider class and must implement
a standard set of APIs that enable other applications to perform transactions.

public class My Application extends ContentProvider {


}

Content URIs
To query a content provider, you specify the query string in the form of a URI which has following
format −
<prefix>://<authority>/<data_type>/<id>
Here is the detail of various parts of the URI −

Sr.No Part & Description

1 prefix
This is always set to content://

authority
2 This specifies the name of the content provider, for example contacts, browser etc. For
third-party content providers, this could be the fully qualified name, such
as com.tutorialspoint.statusprovider

data_type
3 This indicates the type of data that this particular provider provides. For example, if you
are getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like thiscontent://contacts/people

id
4 This specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.
Create Content Provider
This involves number of simple steps to create your own content provider.
 First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
 Second, you need to define your content provider URI address which will be used to access
the content.
 Next you will need to create your own database to keep the content. Usually, Android uses
SQLite database and framework needs to override onCreate() method which will use
SQLite Open Helper method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its Content Providers is called on
the main application thread.
 Next you will have to implement Content Provider queries to perform different database
specific operations.
 Finally register your Content Provider in your activity file using <provider> tag.
Here is the list of methods which you need to override in Content Provider class to have your
Content Provider working −

 onCreate() This method is called when the provider is started.


 query() This method receives a request from a client. The result is returned as a Cursor
object.
 insert()This method inserts a new record into the content provider.
 delete() This method deletes an existing record from the content provider.
 update() This method updates an existing record from the content provider.
 getType() This method returns the MIME type of the data at the given URI.
Create Content Provider
This involves number of simple steps to create your own content provider.
 First of all you need to create a Content Provider class that extends
the ContentProviderbaseclass.
 Second, you need to define your content provider URI address which will be used to access
the content.
 Next you will need to create your own database to keep the content. Usually, Android uses
SQLite database and framework needs to override onCreate() method which will use
SQLite Open Helper method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its Content Providers is called on
the main application thread.
 Next you will have to implement Content Provider queries to perform different database
specific operations.
 Finally register your Content Provider in your activity file using <provider> tag.
Here is the list of methods which you need to override in Content Provider class to have your
Content Provider working −

 onCreate() This method is called when the provider is started.


 query() This method receives a request from a client. The result is returned as a Cursor
object.
 insert()This method inserts a new record into the content provider.
 delete() This method deletes an existing record from the content provider.
 update() This method updates an existing record from the content provider.
 getType() This method returns the MIME type of the data at the given URI.

8) Write a Short note on-


a) Content URI
A content URI is a URI that identifies data in a provider. Content URIs include the symbolic
name of the entire provider (its authority) and a name that points to a table (a path). When you
call a client method to access a table in a provider, the content URI for the table is one of the
arguments.

In the preceding lines of code, the constant CONTENT_URI contains the content URI of the
user dictionary's "words" table. The ContentResolver object parses out the URI's authority, and
uses it to "resolve" the provider by comparing the authority to a system table of known
providers. The ContentResolver can then dispatch the query arguments to the correct provider.
The ContentProvider uses the path part of the content URI to choose the table to access. A
provider usually has a path for each table it exposes.

In the previous lines of code, the full URI for the "words" table is:

content://user_dictionary/words

where the user_dictionary string is the provider's authority, and the words string is the table's
path. The string content:// (the scheme) is always present, and identifies this as a content URI.

Many providers allow you to access a single row in a table by appending an ID value to the end
of the URI. For example, to retrieve a row whose _ID is 4 from user dictionary, you can use this
content URI:

KotlinJava
Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);

You often use id values when you've retrieved a set of rows and then want to update or delete
one of them.

Note: The Uri and Uri.Builder classes contain convenience methods for constructing well-
formed URI objects from strings. The ContentUris class contains convenience methods for
appending id values to a URI. The previous snippet uses withAppendedId() to append an id to
the UserDictionary content URI.

To query a content provider, you specify the query string in the form of a URI which has following
format
<prefix>://<authority>/<data_type>/<id>

Here is the detail of various parts of the URI −

Sr.No Part & Description

prefix
1
This is always set to content://

authority

2 This specifies the name of the content provider, for example contacts, browser etc. For
third-party content providers, this could be the fully qualified name, such
as com.tutorialspoint.statusprovider
data_type

3 This indicates the type of data that this particular provider provides. For example, if you
are getting all the contacts from the Contacts content provider, then the data path would
be people and URI would look like thiscontent://contacts/people

id

4 This specifies the specific record requested. For example, if you are looking for contact
number 5 in the Contacts content provider then URI would look like
this content://contacts/people/5.

b) Working of Content Provider


UI components of android applications like Activity and Fragments use an
object CursorLoader to send query requests to ContentResolver. The ContentResolver
object sends requests (like create, read, update, and delete) to the ContentProvider as a
client. After receiving a request, ContentProvider process it and returns the desired result.
Below is a diagram to represent these processes in pictorial form.

Creating a Content Provider


Following are the steps which are essential to follow in order to create a Content Provider:
 Create a class in the same directory where the that MainActivity file resides and this class
must extend the ContentProvider base class.
 To access the content, define a content provider URI address.
 Create a database to store the application data.
 Implement the six abstract methods of ContentProvider class.
 Register the content provider in AndroidManifest.xml file using <provider> tag.
Following are the six abstract methods and their description which are essential to
override as the part of ContenProvider class:
Abstract Method Description

A method that accepts arguments and fetches the data from the
query() desired table. Data is retired as a cursor object.

To insert a new row in the database of the content provider.


insert() It returns the content URI of the inserted row.

This method is used to update the fields of an existing row.


update() It returns the number of rows updated.

This method is used to delete the existing rows.


delete() It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail Extension(MIME)


getType() type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate() this method immediately to initialise the provider.

c) Methods of Content Provider


Following are the six abstract methods and their description which are essential to
override as the part of ContenProvider class:
Abstract Method Description

A method that accepts arguments and fetches the data from the
query() desired table. Data is retired as a cursor object.
Abstract Method Description

To insert a new row in the database of the content provider.


insert() It returns the content URI of the inserted row.

This method is used to update the fields of an existing row.


update() It returns the number of rows updated.

This method is used to delete the existing rows.


delete() It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail Extension(MIME)


getType() type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate() this method immediately to initialise the provider.

9) Discuss the working mechanism of Content Provider in Android.

You might also like