Professional Documents
Culture Documents
Unit 4 (Questions)
Unit 4 (Questions)
Unit 4 (Questions)
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.
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.
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.
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.
Constructor Description
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.
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.
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.
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();
}
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()};
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.
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 −
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 −
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>
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.
A method that accepts arguments and fetches the data from the
query() desired table. Data is retired as a cursor object.
A method that accepts arguments and fetches the data from the
query() desired table. Data is retired as a cursor object.
Abstract Method Description