SlideShare a Scribd company logo
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!

More Related Content

Similar to Unit - IV (1).pptx

Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
Ivano Malavolta
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
Anuchit Chalothorn
 
QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7
Akash Tyagi
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
GAAD Database presentation
GAAD Database presentationGAAD Database presentation
GAAD Database presentation
Md. Tariqul Islam
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
Mukesh Tekwani
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
MaryadelMar85
 
Based on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docxBased on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docx
JASS44
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
sridharu1981
 
La sql
La sqlLa sql
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
James Johnson
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Sriram Raj
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Zidny Nafan
 
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
sukrithlal008
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
Perfect APK
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
Khaled Anaqwa
 

Similar to Unit - IV (1).pptx (20)

Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7QTP Automation Testing Tutorial 7
QTP Automation Testing Tutorial 7
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
GAAD Database presentation
GAAD Database presentationGAAD Database presentation
GAAD Database presentation
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
Based on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docxBased on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docx
 
Asp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptxAsp .Net Database Connectivity Presentation.pptx
Asp .Net Database Connectivity Presentation.pptx
 
La sql
La sqlLa sql
La sql
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx171_74_216_Module_5-Non_relational_database_-mongodb.pptx
171_74_216_Module_5-Non_relational_database_-mongodb.pptx
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)Android Training (Storing data using SQLite)
Android Training (Storing data using SQLite)
 

More from VaishnaviGaikwad67

reearch-presentation.pptx
reearch-presentation.pptxreearch-presentation.pptx
reearch-presentation.pptx
VaishnaviGaikwad67
 
Unit - III.pptx
Unit - III.pptxUnit - III.pptx
Unit - III.pptx
VaishnaviGaikwad67
 
computer.pptx
computer.pptxcomputer.pptx
computer.pptx
VaishnaviGaikwad67
 
Seaborn visualization.pptx
Seaborn visualization.pptxSeaborn visualization.pptx
Seaborn visualization.pptx
VaishnaviGaikwad67
 
classification.pptx
classification.pptxclassification.pptx
classification.pptx
VaishnaviGaikwad67
 
Unit - IV.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.pptx
VaishnaviGaikwad67
 

More from VaishnaviGaikwad67 (6)

reearch-presentation.pptx
reearch-presentation.pptxreearch-presentation.pptx
reearch-presentation.pptx
 
Unit - III.pptx
Unit - III.pptxUnit - III.pptx
Unit - III.pptx
 
computer.pptx
computer.pptxcomputer.pptx
computer.pptx
 
Seaborn visualization.pptx
Seaborn visualization.pptxSeaborn visualization.pptx
Seaborn visualization.pptx
 
classification.pptx
classification.pptxclassification.pptx
classification.pptx
 
Unit - IV.pptx
Unit - IV.pptxUnit - IV.pptx
Unit - IV.pptx
 

Recently uploaded

[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
hackersuli
 
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
ukwwuq
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
Trending Blogers
 
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
uehowe
 
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
cuobya
 
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
bseovas
 
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
vmemo1
 
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
cuobya
 
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
fovkoyb
 
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
uehowe
 
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalmanuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
wolfsoftcompanyco
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
Design Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptxDesign Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptx
saathvikreddy2003
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
uehowe
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
Danica Gill
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
xjq03c34
 
Azure EA Sponsorship - Customer Guide.pdf
Azure EA Sponsorship - Customer Guide.pdfAzure EA Sponsorship - Customer Guide.pdf
Azure EA Sponsorship - Customer Guide.pdf
AanSulistiyo
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
ysasp1
 

Recently uploaded (20)

[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
 
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
 
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
留学挂科(UofM毕业证)明尼苏达大学毕业证成绩单复刻办理
 
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
 
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
不能毕业如何获得(USYD毕业证)悉尼大学毕业证成绩单一比一原版制作
 
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
重新申请毕业证书(RMIT毕业证)皇家墨尔本理工大学毕业证成绩单精仿办理
 
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
假文凭国外(Adelaide毕业证)澳大利亚国立大学毕业证成绩单办理
 
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
存档可查的(USC毕业证)南加利福尼亚大学毕业证成绩单制做办理
 
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
办理毕业证(NYU毕业证)纽约大学毕业证成绩单官方原版办理
 
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalmanuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
manuaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaal
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
Design Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptxDesign Thinking NETFLIX using all techniques.pptx
Design Thinking NETFLIX using all techniques.pptx
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
办理毕业证(UPenn毕业证)宾夕法尼亚大学毕业证成绩单快速办理
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
 
Azure EA Sponsorship - Customer Guide.pdf
Azure EA Sponsorship - Customer Guide.pdfAzure EA Sponsorship - Customer Guide.pdf
Azure EA Sponsorship - Customer Guide.pdf
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
 

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 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.
  • 3. 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.
  • 5. 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.
  • 6. 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
  • 7. 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.
  • 8. ► 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.
  • 9. ► 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.
  • 10. ► 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
  • 11. SQLiteDatabase ► It is a class which contains methods to be performed on SQLite database such as create, update, delete, select etc.
  • 12. ► 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:
  • 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 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();
  • 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 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.
  • 28. ► 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();
  • 30. 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.
  • 31. 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
  • 32. ► 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.
  • 33. Diagram - how the content provider helps in sharing data with applications from data stores.
  • 34. ► 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.
  • 35. 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 .
  • 36. 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.
  • 37. 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>
  • 38. 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
  • 39. 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 { }