Data Persistence in
Android
- PRESENTED BY –
MRS. N. G. MANDLIK
ASSISTANT PROFESSOR,
DEPARTMENT OF COMPUTER STUDIES,
CSIBER, KOLHAPUR
What is Data persistence?
► Persistence is “the continuance of an effect after its cause is removed.”
► In the context of storing data in a computer system, it means that the data survives
after the process with which it was created has ended.
► In other words, for a data store to be considered persistent, it must write to non-
volatile storage.
Why to persist data?
► Persisting data is important in application development, as users typically expect to
reuse data in the future.
► In Android, there are primarily four basic ways of persisting data-
► A lightweight mechanism known as shared preferences to save small chunks of data.
► Traditional file systems (Internal)
► External systems (Flash drive)
► A relational database management system through the support of SQLite databases.
Android Storage Options
Introducing SQLite
► SQLite is an light-weight, open-source relational database that is used to perform
database operations on android devices such as storing, manipulating or retrieving
persistent data from the database.
► By default, it is embedded in android. So to access this database, there is no need to
establish any connections for it like JDBC,ODBC etc.
► Android has the main package android.database.sqlite that contains the classes to
manage the databases.
► SQLite is considerably, the lighter version of SQL database. It supports standard
relations database features, like SQL syntax, transactions & SQL statements.
SQLite Packages and Classes
► Packages required for designing applications using SQLite are listed below:
► android.database
► android.database.sqlite
► android.content
► Classes required for designing applications using SQLite are listed below:
► android.database.sqlite.SQLiteOpenHelper
► android.database.sqlite.SQliteDatabase
► android.database.Cusor
► android.content.ContentValues
SQLiteOpenHelper
► SQLiteOpenHelper is a class found inside android.database.sqlite package.
► It is a helper class that helps in creating the database, handling the operations and
also the version management.
► For performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.
► To use SQLiteOpenHelper, create a class, and then extend SQLiteOpenHelper inside
the class that has been created.
► The SQLiteOpenHelper only require the DATABASE_NAME to create database.
► Constructors of SQLiteOpenHelper class :
SQLiteOpenHelper
Constructor Description
SQLiteOpenHelper(Context context, String
name, SQLiteDatabase.CursorFactory factory, int
version)
creates an object for creating, opening and
managing the database.
SQLiteOpenHelper(Context context, String
name, SQLiteDatabase.CursorFactory factory, int
version, DatabaseErrorHandler errorHandler)
creates an object for creating, opening and
managing the database. It specifies the error
handler.
► Methods of SQLiteOpenHelper class :
SQLiteOpenHelper
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 oldVersion, int newVersion)
called when database needs to be upgraded.
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, int
oldVersion, int newVersion)
called when database needs to be downgraded.
► Important SQLiteOpenHelper Class Methods-
1. getWritableDatabase()
2. getReadableDatabase()
► Above methods return a reference to SQLiteDatabase as shown in the
following statement-
SQLiteDatabase db = this.getWritableDatabase();
SQLiteOpenHelper
SQLiteDatabase
► It is a class which contains methods to be performed on SQLite database
such as create, update, delete, select etc.
► Methods of SQLiteDatabase class :
SQLiteDatabase
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String nullColumnHack,
ContentValues values)
inserts a record on the database. The table
specifies the table name, nullColumnHack
doesn't allow 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, ContentValues values,
String whereClause, String[ ] whereArgs)
updates a row. It returns the no. of values
affected.
Cursor query(String table, String[ ] columns, String
selection, String[ ] selectionArgs, String groupBy,
String having, String orderBy)
Creates a resultset and returns a cursor over it.
It enables the operations like- Filtering, Sorting,
Grouping, Grouping and Filtering on the data:
Creating a database
► Creating a database with the name “Library”-
public class DatabaseHandler extends SQLiteOpenHelper
{
public DatabaseHandler(Context c)
{
super(c, ”Library”, null, 1);
}
}
context object we will get it
from the activity while
creating the instance name of the database
If we want a cursor to be initialized on the
creation we can use cursor factory, it is optionall
and that is why we passed null
Database version
Creating a database
► Creating a “student” table in “Library” Database -
public void onCreate(SQLiteDatabase db)
{
db.execSQL(“CREATE TABLE student(rollno INTEGER PRIMARY
KEY,
name TEXT)”);
}
method of SQLiteDatabase class which accepts
the SQL query to be executed.
Performing database operations
1. Inserting a Record in a “student” table-
► Step-1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( )
method of Context class as-
SQLiteDatabase db = this.getWritableDatabase( );
► Step-2 : Create an object of ContentValues class by invoking a default constructor.
ContentValues c = new ContentValues( );
► Step-3 : Invoke put( ) method of ContentValues class which accepts two parameters, the first
parameter is a column name and the second parameter is a value.
c.put(“column_name”,”column_value”);
Performing database operations
1. Inserting a Record in a “student” table-
► Step-4 : Invoke insert() method of SQLiteDatabase class which accepts the following three
parameters:
► The first parameter is the String object specifying the name of the table in which the
record must be inserted.
► The second parameter is “null” which means “null” value should be stored in a column
if the value is empty.
► The third parameter is an instance of ContentValues class containing the values to be
inserted in different columns of a table.
Performing database operations
1. Inserting a Record in a “student” table-
► For Example-
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(“rollno‖”,1);
c.put(“name”, “xyz”);
db.insert(“student”, null, c);
db.close ();
Performing database operations
2. Updating a Record in a “student” table- Changing name of rollno 1 to ‘abc’
► Step-1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( )
method of Context class as-
SQLiteDatabase db = this.getWritableDatabase( );
► Step-2 : Create an object of ContentValues class by invoking a default constructor.
ContentValues c = new ContentValues( );
► Step-3 : Invoke put( ) method of ContentValues class which accepts two parameters, the first
parameter is a column name and the second parameter is a value.
c.put(“column_name”,”column_value”);
Performing database operations
2. Updating a Record in a “student” table- Changing name of rollno 1 to ‘abc’
► Step-4 : Invoke update() method of SQLiteDatabase class which accepts the following four
parameters:
► The first parameter is a String object specifying the name of the table to be updated.
► The second parameter is an instance of ContentValues class containing updated values.
► The third parameter is a condition containing ‘?‘ place holder for runtime parameters.
► The fourth parameter is a String array supplying values for place holders of argument 3.
Performing database operations
2. Updating a Record in a “student” table- Changing name of rollno 1 to ‘abc’
► For Example-
SQLiteDatabase db = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(name,“abc");
db.update("student", c, "rollno = ?", new String [] {"1"});
db.close();
Performing database operations
3. Deleting a Record from a student table- Delete a Record with Rollno 2
► Step-1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( )
method of Context class as-
SQLiteDatabase db = this.getWritableDatabase( );
► Step-2 : Invoke delete() method of SQLiteDatabase class which accepts the following three
parameters:
►The first parameter is a String object specifying the name of the table from which the record
is deleted.
►The second parameter is a condition containing ‘?‘ place holder for runtime parameters.
►The third parameter is a String array supplying values for place holders of argument 2.
Performing database operations
3. Deleting a Record from a student table- Delete a Record with Rollno 2
► For Example-
SQLiteDatabase db = this.getWritableDatabase();
db.delete(“student”, “rollno = ?”, new String [] {“2”});
db.close();
Performing database operations
4. Retrieving all Records from a student table
Method 1: Using query() method of SQLiteDatabase Class - The main steps involved in creating a
cursor over a result set retrieved from a “student‟ table are-
► Step - 1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( )
method of Context class as-
SQLiteDatabase db = this.getWritableDatabase( );
► Step - 2 : Invoke query() method of SQLiteDatabase class which accepts the following seven
parameters:
►The first parameter is a String object specifying the name of the table.
►The second parameter is the array of string objects containing the column names.
►The third parameter is a filter string.
► The fourth parameter is a String array containing filter parameters.
► The fifth parameter is a String object specifying the name of GroupBy column.
► The sixth parameter is ‘Having’ condition
► The seventh parameter is a String object specifying the sort column name.
SQLiteDatabase db = this.getWritableDatabase();
Cusor c = db.query(“student”, new
String[] {“rollno”, “name”}, null, null, null, null, null);
db.close();
Performing database operations
4. Retrieving all Records from a student table
Method 2: Using rawQuery() method of SQLiteDatabase Class - The main steps involved in
creating a cursor over a result set retrieved from a “student‟ table are-
► Step - 1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( )
method of Context class as-
SQLiteDatabase db = this.getWritableDatabase( );
► Step - 2 : Invoke rawQuery() method of SQLiteDatabase class which accepts the following two
parameters:
► The first parameter is a SELECT query which may contain a runtime parameter specified by ‘ ? ’.
► The second parameter is an array of String objects specifying runtime parameter value or null, if
runtime parameters are not present.
SQLiteDatabase db = this.getWritableDatabase ();
Cursor c= db.rawQuery(“SELECT * FROM student”, null);
db.close();
Navigating Through the Records of
a student table
► The Cursor class supports the following methods for navigating through the records of
result set.
Method Description
moveToFirst() Moves the pointer to the first record of result set.
moveToNext() Moves the pointer to the next record of result set.
getX() Retrieves the value of the column with the specified index
(index starts at 0) of the record at the current cursor position.
X is any valid column type.
► For example,
SQLiteDatabase db = this.getWritableDatabase ();
Cursor c= db.rawQuery(“SELECT * FROM student”, null);
int rollno, String name;
StringBuffer sb=new StringBuffer();
if (c.moveToFirst()) {
do {
rollno = c.getInt(0);
name = c.getString(1);
sb.append(String.valueOf(rollno));
sb.append(“ “);
sb.append(name);
sb.append(“n”);
} while (c.moveToNext());
}
db.close();
Content Providers
in Android
What is Content Provider?
► Do you know how applications share data?
► All kinds of data sharing among the applications are available due to the content
provider.
► Content Providers act as a medium for various applications to communicate with each
other.
► The role of the content provider in the android system is like a central repository in which
data of the applications are stored, and it facilitates other applications to securely access and
modifies that data based on the user requirements.
► It manages and looks over the application data like images, audio, videos, and personal
contact information and accesses the SQLite Database.
What is Content Provider?
► In order to share the data, content providers have certain permissions that are used to grant
or restrict the rights to other applications to interfere with the data.
► All the seeking of data is done through the content provider itself. Whenever you require
access to data from other applications, the content provider seeks permission from the user
to access the data to the other application.
► For Example, Whenever any application needs to access some pictures from the gallery, it seeks
your permission, and the content provider provides you with the required content.
► Some of the examples of Content Providers in Android are-
► Music Playlist has a list of songs.
► Calls Logs contain the call details.
► Contact List that contain Contact details.
► Message Threads
► Gallery Application that contains images
► File Manager, etc
► 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.
Diagram - how the content provider helps in sharing data with applications
from data stores.
► Four basic operations known as CRUD Operations provided by the
content provider are-
C – Create : It is used for the creation of data in content providers.
R – Read : It reads the data stored in the content provider.
U – Update : It lets the editing in existing data in content providers.
D – Delete : It deletes the existing data stored in its Storage.
Working of Content Provider in Android
(Accessing Data with Content Provider)
► We need to establish a connection using the “ContentResolver”
object to get the data from the content provider.
► The ContentResolver object helps the application to communicate
with the Content Provider.
► In the next step, we need to connect ContentResolver object with the
user interface.
► We require another object called “CursorLoader” so the user can
interact directly with the Content Provider by using the user
interface.
► The CursorLoader receives the user’s query request and forward it to
the Content Provider.
► The content Provider executes the query and provides the requested
data to the user .
Methods of Content Provider
It receives a request from the client. By using arguments it will get a data from
the requested table and return the data as a Cursor object.
To insert a new row in the database of the content provider. It returns the
content URI of the inserted row.
This method will update existing rows in content provider and returns the
number of rows updated.
This method will delete the rows in content provider and returns the number of
rows deleted.
It returns the Multipurpose Internet Mail Extension type of data to the given
Content URI.
As the content provider is created, the android system calls this method
immediately to initialise the provider.
Content URIs in Android
► Content URI(Uniform Resource Identifier) is the key concept of Content providers
which identifies the data in the content providers.
► To access the data from a content provider, URI is used as a query string.
► Based on the Content URI, we get the required data.
► The structure of any Content URI can be divided into four types:
<prefix>://<authority>/<path>/<optional_id>
Content URIs in Android
► Details of different parts of Content URI:
► Prefix - Mandatory part of the URI as it represents that the given URI is a Content URI. Usually,
the prefix is set to content://.
► Authority – It is the unique name of the content provider, like photos, contacts for in-built
content providers. Generally Authority is the name of the package in which ContentProvider is
registered. For example, com.example.contentproviderdemo.MycontentProvider
► Path – It contains the location of the data. It is mostly used to identify individual tables. For
example, for retrieving the contacts from the “Contacts‟ content provider, the path would be
people and the format of URI is,
content://contacts/people
► ID – This is an optional parameter that is used to access specific records. For example, in the
case of “Contacts‟ content provider, for retrieving the contact no. 1, the format of the URI is,
content://contacts/people/1
Implementing Content Provider in Android
► 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.
► A typical declaration of content provider is shown below:
public class MyContentProvider extends ContentProvider {
}
Thank You!

Unit - IV (1).pptx

  • 1.
    Data Persistence in Android -PRESENTED BY – MRS. N. G. MANDLIK ASSISTANT PROFESSOR, DEPARTMENT OF COMPUTER STUDIES, CSIBER, KOLHAPUR
  • 2.
    What is Datapersistence? ► Persistence is “the continuance of an effect after its cause is removed.” ► In the context of storing data in a computer system, it means that the data survives after the process with which it was created has ended. ► In other words, for a data store to be considered persistent, it must write to non- volatile storage.
  • 3.
    Why to persistdata? ► Persisting data is important in application development, as users typically expect to reuse data in the future. ► In Android, there are primarily four basic ways of persisting data- ► A lightweight mechanism known as shared preferences to save small chunks of data. ► Traditional file systems (Internal) ► External systems (Flash drive) ► A relational database management system through the support of SQLite databases.
  • 4.
  • 5.
    Introducing SQLite ► SQLiteis an light-weight, open-source relational database that is used to perform database operations on android devices such as storing, manipulating or retrieving persistent data from the database. ► By default, it is embedded in android. So to access this database, there is no need to establish any connections for it like JDBC,ODBC etc. ► Android has the main package android.database.sqlite that contains the classes to manage the databases. ► SQLite is considerably, the lighter version of SQL database. It supports standard relations database features, like SQL syntax, transactions & SQL statements.
  • 6.
    SQLite Packages andClasses ► Packages required for designing applications using SQLite are listed below: ► android.database ► android.database.sqlite ► android.content ► Classes required for designing applications using SQLite are listed below: ► android.database.sqlite.SQLiteOpenHelper ► android.database.sqlite.SQliteDatabase ► android.database.Cusor ► android.content.ContentValues
  • 7.
    SQLiteOpenHelper ► SQLiteOpenHelper isa class found inside android.database.sqlite package. ► It is a helper class that helps in creating the database, handling the operations and also the version management. ► For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class. ► To use SQLiteOpenHelper, create a class, and then extend SQLiteOpenHelper inside the class that has been created. ► The SQLiteOpenHelper only require the DATABASE_NAME to create database.
  • 8.
    ► Constructors ofSQLiteOpenHelper class : SQLiteOpenHelper Constructor Description SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) creates an object for creating, opening and managing the database. SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) creates an object for creating, opening and managing the database. It specifies the error handler.
  • 9.
    ► Methods ofSQLiteOpenHelper class : SQLiteOpenHelper 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 oldVersion, int newVersion) called when database needs to be upgraded. public synchronized void close () closes the database object. public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) called when database needs to be downgraded.
  • 10.
    ► Important SQLiteOpenHelperClass Methods- 1. getWritableDatabase() 2. getReadableDatabase() ► Above methods return a reference to SQLiteDatabase as shown in the following statement- SQLiteDatabase db = this.getWritableDatabase(); SQLiteOpenHelper
  • 11.
    SQLiteDatabase ► It isa class which contains methods to be performed on SQLite database such as create, update, delete, select etc.
  • 12.
    ► Methods ofSQLiteDatabase class : SQLiteDatabase Method Description void execSQL(String sql) executes the sql query not select query. long insert(String table, String nullColumnHack, ContentValues values) inserts a record on the database. The table specifies the table name, nullColumnHack doesn't allow 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, ContentValues values, String whereClause, String[ ] whereArgs) updates a row. It returns the no. of values affected. Cursor query(String table, String[ ] columns, String selection, String[ ] selectionArgs, String groupBy, String having, String orderBy) Creates a resultset and returns a cursor over it. It enables the operations like- Filtering, Sorting, Grouping, Grouping and Filtering on the data:
  • 13.
    Creating a database ►Creating a database with the name “Library”- public class DatabaseHandler extends SQLiteOpenHelper { public DatabaseHandler(Context c) { super(c, ”Library”, null, 1); } } context object we will get it from the activity while creating the instance name of the database If we want a cursor to be initialized on the creation we can use cursor factory, it is optionall and that is why we passed null Database version
  • 14.
    Creating a database ►Creating a “student” table in “Library” Database - public void onCreate(SQLiteDatabase db) { db.execSQL(“CREATE TABLE student(rollno INTEGER PRIMARY KEY, name TEXT)”); } method of SQLiteDatabase class which accepts the SQL query to be executed.
  • 15.
    Performing database operations 1.Inserting a Record in a “student” table- ► Step-1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( ) method of Context class as- SQLiteDatabase db = this.getWritableDatabase( ); ► Step-2 : Create an object of ContentValues class by invoking a default constructor. ContentValues c = new ContentValues( ); ► Step-3 : Invoke put( ) method of ContentValues class which accepts two parameters, the first parameter is a column name and the second parameter is a value. c.put(“column_name”,”column_value”);
  • 16.
    Performing database operations 1.Inserting a Record in a “student” table- ► Step-4 : Invoke insert() method of SQLiteDatabase class which accepts the following three parameters: ► The first parameter is the String object specifying the name of the table in which the record must be inserted. ► The second parameter is “null” which means “null” value should be stored in a column if the value is empty. ► The third parameter is an instance of ContentValues class containing the values to be inserted in different columns of a table.
  • 17.
    Performing database operations 1.Inserting a Record in a “student” table- ► For Example- SQLiteDatabase db = this.getWritableDatabase(); ContentValues c = new ContentValues(); c.put(“rollno‖”,1); c.put(“name”, “xyz”); db.insert(“student”, null, c); db.close ();
  • 18.
    Performing database operations 2.Updating a Record in a “student” table- Changing name of rollno 1 to ‘abc’ ► Step-1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( ) method of Context class as- SQLiteDatabase db = this.getWritableDatabase( ); ► Step-2 : Create an object of ContentValues class by invoking a default constructor. ContentValues c = new ContentValues( ); ► Step-3 : Invoke put( ) method of ContentValues class which accepts two parameters, the first parameter is a column name and the second parameter is a value. c.put(“column_name”,”column_value”);
  • 19.
    Performing database operations 2.Updating a Record in a “student” table- Changing name of rollno 1 to ‘abc’ ► Step-4 : Invoke update() method of SQLiteDatabase class which accepts the following four parameters: ► The first parameter is a String object specifying the name of the table to be updated. ► The second parameter is an instance of ContentValues class containing updated values. ► The third parameter is a condition containing ‘?‘ place holder for runtime parameters. ► The fourth parameter is a String array supplying values for place holders of argument 3.
  • 20.
    Performing database operations 2.Updating a Record in a “student” table- Changing name of rollno 1 to ‘abc’ ► For Example- SQLiteDatabase db = this.getWritableDatabase(); ContentValues c = new ContentValues(); c.put(name,“abc"); db.update("student", c, "rollno = ?", new String [] {"1"}); db.close();
  • 21.
    Performing database operations 3.Deleting a Record from a student table- Delete a Record with Rollno 2 ► Step-1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( ) method of Context class as- SQLiteDatabase db = this.getWritableDatabase( ); ► Step-2 : Invoke delete() method of SQLiteDatabase class which accepts the following three parameters: ►The first parameter is a String object specifying the name of the table from which the record is deleted. ►The second parameter is a condition containing ‘?‘ place holder for runtime parameters. ►The third parameter is a String array supplying values for place holders of argument 2.
  • 22.
    Performing database operations 3.Deleting a Record from a student table- Delete a Record with Rollno 2 ► For Example- SQLiteDatabase db = this.getWritableDatabase(); db.delete(“student”, “rollno = ?”, new String [] {“2”}); db.close();
  • 23.
    Performing database operations 4.Retrieving all Records from a student table Method 1: Using query() method of SQLiteDatabase Class - The main steps involved in creating a cursor over a result set retrieved from a “student‟ table are- ► Step - 1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( ) method of Context class as- SQLiteDatabase db = this.getWritableDatabase( ); ► Step - 2 : Invoke query() method of SQLiteDatabase class which accepts the following seven parameters: ►The first parameter is a String object specifying the name of the table. ►The second parameter is the array of string objects containing the column names. ►The third parameter is a filter string.
  • 24.
    ► The fourthparameter is a String array containing filter parameters. ► The fifth parameter is a String object specifying the name of GroupBy column. ► The sixth parameter is ‘Having’ condition ► The seventh parameter is a String object specifying the sort column name. SQLiteDatabase db = this.getWritableDatabase(); Cusor c = db.query(“student”, new String[] {“rollno”, “name”}, null, null, null, null, null); db.close();
  • 25.
    Performing database operations 4.Retrieving all Records from a student table Method 2: Using rawQuery() method of SQLiteDatabase Class - The main steps involved in creating a cursor over a result set retrieved from a “student‟ table are- ► Step - 1 : Obtain a reference to SQLiteDatabase class object by invoking getWritableDatabase( ) method of Context class as- SQLiteDatabase db = this.getWritableDatabase( ); ► Step - 2 : Invoke rawQuery() method of SQLiteDatabase class which accepts the following two parameters: ► The first parameter is a SELECT query which may contain a runtime parameter specified by ‘ ? ’. ► The second parameter is an array of String objects specifying runtime parameter value or null, if runtime parameters are not present.
  • 26.
    SQLiteDatabase db =this.getWritableDatabase (); Cursor c= db.rawQuery(“SELECT * FROM student”, null); db.close();
  • 27.
    Navigating Through theRecords of a student table ► The Cursor class supports the following methods for navigating through the records of result set. Method Description moveToFirst() Moves the pointer to the first record of result set. moveToNext() Moves the pointer to the next record of result set. getX() Retrieves the value of the column with the specified index (index starts at 0) of the record at the current cursor position. X is any valid column type.
  • 28.
    ► For example, SQLiteDatabasedb = this.getWritableDatabase (); Cursor c= db.rawQuery(“SELECT * FROM student”, null); int rollno, String name; StringBuffer sb=new StringBuffer(); if (c.moveToFirst()) { do { rollno = c.getInt(0); name = c.getString(1); sb.append(String.valueOf(rollno)); sb.append(“ “); sb.append(name); sb.append(“n”); } while (c.moveToNext()); } db.close();
  • 29.
  • 30.
    What is ContentProvider? ► Do you know how applications share data? ► All kinds of data sharing among the applications are available due to the content provider. ► Content Providers act as a medium for various applications to communicate with each other. ► The role of the content provider in the android system is like a central repository in which data of the applications are stored, and it facilitates other applications to securely access and modifies that data based on the user requirements. ► It manages and looks over the application data like images, audio, videos, and personal contact information and accesses the SQLite Database.
  • 31.
    What is ContentProvider? ► In order to share the data, content providers have certain permissions that are used to grant or restrict the rights to other applications to interfere with the data. ► All the seeking of data is done through the content provider itself. Whenever you require access to data from other applications, the content provider seeks permission from the user to access the data to the other application. ► For Example, Whenever any application needs to access some pictures from the gallery, it seeks your permission, and the content provider provides you with the required content. ► Some of the examples of Content Providers in Android are- ► Music Playlist has a list of songs. ► Calls Logs contain the call details. ► Contact List that contain Contact details. ► Message Threads ► Gallery Application that contains images ► File Manager, etc
  • 32.
    ► Content providerslet 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.
  • 33.
    Diagram - howthe content provider helps in sharing data with applications from data stores.
  • 34.
    ► Four basicoperations known as CRUD Operations provided by the content provider are- C – Create : It is used for the creation of data in content providers. R – Read : It reads the data stored in the content provider. U – Update : It lets the editing in existing data in content providers. D – Delete : It deletes the existing data stored in its Storage.
  • 35.
    Working of ContentProvider in Android (Accessing Data with Content Provider) ► We need to establish a connection using the “ContentResolver” object to get the data from the content provider. ► The ContentResolver object helps the application to communicate with the Content Provider. ► In the next step, we need to connect ContentResolver object with the user interface. ► We require another object called “CursorLoader” so the user can interact directly with the Content Provider by using the user interface. ► The CursorLoader receives the user’s query request and forward it to the Content Provider. ► The content Provider executes the query and provides the requested data to the user .
  • 36.
    Methods of ContentProvider It receives a request from the client. By using arguments it will get a data from the requested table and return the data as a Cursor object. To insert a new row in the database of the content provider. It returns the content URI of the inserted row. This method will update existing rows in content provider and returns the number of rows updated. This method will delete the rows in content provider and returns the number of rows deleted. It returns the Multipurpose Internet Mail Extension type of data to the given Content URI. As the content provider is created, the android system calls this method immediately to initialise the provider.
  • 37.
    Content URIs inAndroid ► Content URI(Uniform Resource Identifier) is the key concept of Content providers which identifies the data in the content providers. ► To access the data from a content provider, URI is used as a query string. ► Based on the Content URI, we get the required data. ► The structure of any Content URI can be divided into four types: <prefix>://<authority>/<path>/<optional_id>
  • 38.
    Content URIs inAndroid ► Details of different parts of Content URI: ► Prefix - Mandatory part of the URI as it represents that the given URI is a Content URI. Usually, the prefix is set to content://. ► Authority – It is the unique name of the content provider, like photos, contacts for in-built content providers. Generally Authority is the name of the package in which ContentProvider is registered. For example, com.example.contentproviderdemo.MycontentProvider ► Path – It contains the location of the data. It is mostly used to identify individual tables. For example, for retrieving the contacts from the “Contacts‟ content provider, the path would be people and the format of URI is, content://contacts/people ► ID – This is an optional parameter that is used to access specific records. For example, in the case of “Contacts‟ content provider, for retrieving the contact no. 1, the format of the URI is, content://contacts/people/1
  • 39.
    Implementing Content Providerin Android ► 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. ► A typical declaration of content provider is shown below: public class MyContentProvider extends ContentProvider { }
  • 40.