You are on page 1of 98

DONG NAI UNIVERSITY OF TECHNOLOGY

1. Files
2. XML Parser
3. Shared Preferences
4. SQLite
5. Content Provider

DONG NAI UNIVERSITY OF TECHNOLOGY

Android Files

Uses the same file constructions found in a typical


Java application
Files can be stored in the devices (small) main
memory or in the much larger SD card.
Files stored in the devices memory, stay together
with other applications resources (such as icons,
pictures, music, ). We will call this type: Resource
Files.

DONG NAI UNIVERSITY OF TECHNOLOGY

Data storage options

Shared Preferences Store private primitive data in


key-value pairs.
Internal Storage Store private data on the devices
memory.
External Storage Store public data on the shared
external storage.
SQLite Databases Store structured data in a
private/public database.
Network Connection Store data on the web with
your own network server.

DONG NAI UNIVERSITY OF TECHNOLOGY

1. Files
1.1 Internal Storage
1.2 External Storage
1.3 Saving Cache files

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Internal Storage


Reading Resource File : Everything in the apk will
be read only. And it's even better: android doesn't
extract the apk when you install a program, so the
size consumed is kept to minimal.

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Internal Storage

Reading Resource
File

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Internal Storage


If you want to Read and Write an internal
file:
File is stored in the phones memory under:

/data/data/app/files

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Internal Storage

Reading an internal
File

DONG NAI UNIVERSITY OF TECHNOLOGY

1.1 Internal Storage

Writing an internal
File

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 External Storage


Reading/Writing to External Devices SD card. SD card
has the obvious advantage of a larger working space.

10

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 External Storage

Reading

11

DONG NAI UNIVERSITY OF TECHNOLOGY

1.2 External Storage

Writing

12

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Saving Cache files


To speed up your applications performance and how often it
accesses the networkcreate a cache file.
Cache files are stored in the following location on the Android
file system:/data/data/app/cache
Click icon to
pull or push
file

13

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Saving Cache files


If you'd like to cache some data, rather than store it
persistently, you should use getCacheDir() to open a File
that represents the internal directory where your
application should save temporary cache files.
When the device is low on internal storage space,
Android may delete these cache files to recover space.
However, you should not rely on the system to clean up
these files for you. You should always maintain the cache
files yourself and stay within a reasonable limit of space
consumed, such as 1MB. When the user uninstalls your
application, these files are removed.

14

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Saving Cache files

Creating cache file

15

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Saving Cache files

Reading cache file

16

DONG NAI UNIVERSITY OF TECHNOLOGY

1.3 Saving Cache files

Get all cache files

17

DONG NAI UNIVERSITY OF TECHNOLOGY

2. XML Parser
2.1 Whats XML?
2.2 How is XML used?
2.3 Parsing XML by DOM
2.4 Parsing XML by SAX

18

DONG NAI UNIVERSITY OF TECHNOLOGY

2.1 Whats XML?


Extensible Markup Language (XML) is a set of rules for
encoding documents in a readable form.
Similar to HTML but <tagElements> are user-defined.
It is defined in the XML Specification produced by the W3C.
XML's design goals emphasize transparency, simplicity,
and transportability over the Internet.
Example of XML-based languages include: RSS , Atom,
SOAP, and XHTML.
Several office productivity tools default to XML format for
internal data storage. Example: Microsoft Office,
OpenOffice.org, and Apple's iWork.
19

DONG NAI UNIVERSITY OF TECHNOLOGY

2.2 How is XML used?


XML is used for defining and documenting object
classes.
For example, an XML document (.xml) might contain a
collection of complex employee elements, such as
<employee id= title= >...</employee> which
lexically includes an id and title attributes.
Employee may also hold other inner elements such as
name, country, city, and zip.
An XML-Data schema (.xsd) can describe such syntax.

20

DONG NAI UNIVERSITY OF TECHNOLOGY

2.2 How is XML used?

21

DONG NAI UNIVERSITY OF TECHNOLOGY

2.3 Parsing XML by DOM


DOM : W3C DocumentBuilder Parser
Document Object Model
Cache all
Standard tree structure

Parsing this XML

22

DONG NAI UNIVERSITY OF TECHNOLOGY

2.3 Parsing XML by DOM


The XML file is given to the W3C parser to construct an
equivalent tree.
Elements from the XML file are represented in the parsetree as NodeLists. These ArrayList-like collections are made
with the .getElementsByTagName() method.
An individual node from a NodeList could be explored using
the methods:
.item(i), .getName() , .getValue() , .getFirstChild() ,
.getAttributes(),

23

DONG NAI UNIVERSITY OF TECHNOLOGY

2.3 Parsing XML by DOM


Creating

a Java DOM XML parser is done using the


javax.xml.parsers.DocumentBuilderFactory class.

Parsing an XML file into a DOM tree

24

DONG NAI UNIVERSITY OF TECHNOLOGY

2.3 Parsing XML by DOM

25

DONG NAI UNIVERSITY OF TECHNOLOGY

2.3 Parsing XML by DOM


The two most commonly used features of DOM are:
Accessing Child Elements of an Element
Accessing Attributes of an Element
At the top is the Document object. The Document object has
a single root element
Element root = doc.getDocumentElement();
get the children of an element
get the attribute of an element
get the data of an element
element.getTextContent();
26

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX


SAX
Simple API for XML
scan the document
Less memory
Faster
Complex

Parsing this
XML

27

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX


A SAX
XmlPullParser is used to scan the document using
the .next() method and detect the main eventTypes
START_TAG TEXT END_TAG END_DOCUMENT
When the beginning of a tag is recognized, we use the
.getName() method to grab the tag name.
We use the method .getText() to extract data after TEXT
event.

28

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX


Attributes

from an element can be extracted using the

methods:
.getAttributeCount()
.getAttributeName()
.getAttributeValue()

29

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX


Using

the XmlPullParser class to generate


scanner/parser to traverse an XML document

30

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX

31

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX

32

DONG NAI UNIVERSITY OF TECHNOLOGY

2.4 Parsing XML by SAX

33

DONG NAI UNIVERSITY OF TECHNOLOGY

3. Shared Preferences
3.1 Creating and Saving Preferences
3.2 Saving and Restoring Instance State
3.3 Shared Preference Change Listeners
3.4 Activity and Framework Preferences

34

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Creating and Saving Preferences


To create or modify a Shared Preference, call
getSharedPreferences on the application Context,
passing in the name of the Shared Preference to change.
Shared Preferences are shared across an applications
components, but arent available to other applications.
To modify a Shared Preference use the
SharedPreferences.Editor class. Get the Editor object
by calling edit on the Shared Preferences object you want
to change. To save edits call commit on the Editor.

35

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Creating and Saving Preferences

Checked and then click Login

Re open
application
information are
restored
36

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Creating and Saving Preferences

37

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Creating and Saving Preferences

38

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Creating and Saving Preferences

39

DONG NAI UNIVERSITY OF TECHNOLOGY

3.1 Creating and Saving Preferences

The saving
location of
Preferences

XML format

40

DONG NAI UNIVERSITY OF TECHNOLOGY

.2 Saving and Restoring Instance State


If you want to save Activity information that doesnt need
to be shared with other components (e.g., class instance
variables), you can call Activity.getPreferences() without
specifying a Shared Preferences name. Access to the
returned Shared Preferences map is restricted to the
calling Activity; each Activity supports a single unnamed
Shared Preferences object.

41

DONG NAI UNIVERSITY OF TECHNOLOGY

.2 Saving and Restoring Instance State

42

DONG NAI UNIVERSITY OF TECHNOLOGY

.2 Saving and Restoring Instance State


To save Activity instance variables, Android offers a
specialized variation of Shared Preferences. By
overriding an Activitys onSaveInstanceState event
handler, you can use its Bundle parameter to save UI
instance values. Store values using the same get and
put methods as shown for Shared Preferences, before
passing the modified Bundle into the superclasss
handler

43

DONG NAI UNIVERSITY OF TECHNOLOGY

.2 Saving and Restoring Instance State

Its important to remember that onSaveInstanceState is called


only when an Activity becomes inactive, and not when it is
being closed by a call to finish or by the users pressing the
back button.
44

DONG NAI UNIVERSITY OF TECHNOLOGY

.3 Shared Preference Change Listeners


The onSharedPreferenceChangeListener is a useful
class that can be implemented to invoke a callback
whenever a particular Shared Preference value is added,
removed, or modified.
This is particularly useful for Activities and Services that
use the Shared Preference framework to set application
preferences. Using this handler your application
components can listen for changes to user preferences
and update their UIs or behavior as required.

45

DONG NAI UNIVERSITY OF TECHNOLOGY

.3 Shared Preference Change Listeners

46

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences


Android offers an XML-driven framework to create system-style
preference screens for your applications. By using this framework you
can ensure that the preference Activities in your applications are
consistent with those used in both native and other third-party
applications.

The Preference Activity framework consists of three parts:


Preference Screen Layout An XML file that defines the
hierarchy displayed in your Preference Activity. It specifies
the controls to display, the values to allow, and the Shared
Preference keys to use for each UI control.
Preference Activity An extension of PreferenceActivity
that will be used to host your application preference screens.
Shared Preference Change Listener An implementation
of the onSharedPreferenceChangeListener class used to
listen for changes to Shared Preferences.
47

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences

1. Create Preference Layout

48

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences

1. Create Preference Layout

he preference Layout will be stored in res/xml folder


49

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences


CheckBoxPreference A standard preference checkbox
control. Used to set preferences to true or false.
EditTextPreference Allows users to enter a string value
as a preference. Selecting the preference text will display a
text entry dialog.
ListPreference The preference equivalent of a spinner.
Selecting this preference will display a dialog box
containing a list of values from which to select. You can
specify different arrays to contain the display text and
selection values.
RingtonePreference A specialized List Preference that
presents the list of available ringtones for user selection.
This is particularly useful when youre constructing a screen
to configure notification settings.
50

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences

. Create Activity for Preference Layout


Extends from PreferenceActivity class

3. Config manifest xml

51

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences


4. Modify MainActivity

52

DONG NAI UNIVERSITY OF TECHNOLOGY

3.4 Activity and Framework Preferences

SettingActivity
SettingActivity

MainActivity

Information get from MainActivity


53

DONG NAI UNIVERSITY OF TECHNOLOGY

4. SQLite
4.1 Introduction
4.2 Creating Database
4.3 Creating Table
4.4 Action Query:Insert, Update, Delete
4.5 Querying SQLite
4.6 Simple Database Demo

54

DONG NAI UNIVERSITY OF TECHNOLOGY

4.1 Introduction
Embedded standalone program called sqlite3

1.SQLite implements most of the SQL-92 standard


for SQL.
2.support for triggers and allows most complex
queries (exception made for outer joins).
3.SQLITE does not implement referential integrity
constraints through the foreign key constraint model.
4.SQLite uses a relaxed data typing model.
5.Instead of assigning a type to an entire column,
types are assigned to individual values. This is
similar to the Variant type in Visual Basic.
6.Therefore it is possible to insert a string into
numeric column and so on.
55

DONG NAI UNIVERSITY OF TECHNOLOGY

4.2 Creating Database


The simplest way to create a new SQLiteDatabase instance
for your application is to use the openOrCreateDatabase()
method of your application Context
import
android.database.sqlite.SQLiteDatabase;

56

DONG NAI UNIVERSITY OF TECHNOLOGY

4.2 Creating Database


Storing Database directory:
/data/data/app/databases/<databasename>
So, in this case, the path to the database would be:

57

DONG NAI UNIVERSITY OF TECHNOLOGY

4.2 Creating Database


Beware of sharing issues. You cannot access internal
databases belonging to other people (instead use Content
Providers or external SD resident DBs).
An SD resident database requires the Manifest to include:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

58

DONG NAI UNIVERSITY OF TECHNOLOGY

4.3 Creating Table

59

DONG NAI UNIVERSITY OF TECHNOLOGY

Inserting Records:
4.4 Action Query:Insert, Update, Delete
We use the insert() method to add new data to our tables.
We use the ContentValues object to pair the column names
to the column values for the record we want to insert.

60

DONG NAI UNIVERSITY OF TECHNOLOGY

Updating Records:
4.4 Action Query:Insert, Update, Delete
You can modify records in the database using the update()
method.The update() method takes four arguments:
The table to update records
A ContentValues object with the modified fields to update
An optional WHERE clause, in which ? identifies a
WHERE clause argument
An array of WHERE clause arguments, each of which is
substituted in place of the ?s from the second parameter
public int update (String table,
ContentValues values,
String whereClause, String[]
This
method Returns the number of rows
whereArgs)
affected
61

DONG NAI UNIVERSITY OF TECHNOLOGY

Updating Records:
4.4 Action Query:Insert, Update, Delete

Because we are not updating the other fields, we do not need


to include them in the ContentValues object.We include only
the tenlop field because it is the only field we change.
62

DONG NAI UNIVERSITY OF TECHNOLOGY

Deleting Records:
4.4 Action Query:Insert, Update, Delete
You can remove records from the database using the remove()
method.The remove() method takes 3 arguments:
The table to delete the record from
An optional WHERE clause, in which ? identifies a WHERE
clause argument
An array of WHERE clause arguments, each of which is
substituted in place of the ?s from the second parameter
Passing null to the WHERE clause deletes all records in the
table.
public int delete (String table,
String whereClause,
String[] whereArgs)
This method Returns the number of rows
affected
63

DONG NAI UNIVERSITY OF TECHNOLOGY

Deleting Records:
4.4 Action Query:Insert, Update, Delete
Delete all rows in table tblop:
Delete row with malop=dhth7c:

delete method will return the number of rows


affected

64

DONG NAI UNIVERSITY OF TECHNOLOGY

4.5 Querying SQLite


When results are returned from a SQL query, you often
access them using a Cursor found in the
android.database.Cursor class. Cursor objects are like file
pointers; they allow random access to query results.
public Cursor query (String table, String[] columns,
String selection, String[] selectionArgs, String
groupBy, String having, String orderBy)
Returns
A Cursor object, which is positioned before the first entry. Note that Cursors
are not synchronized

65

DONG NAI UNIVERSITY OF TECHNOLOGY

4.5 Querying SQLite


table

The table name to compile the query against.

columns

A list of which columns to return. Passing null will return all columns, which
is discouraged to prevent reading data from storage that isn't going to be
used.

selection

A filter declaring which rows to return, formatted as an SQL WHERE clause


(excluding the WHERE itself). Passing null will return all rows for the given
table.

You may include ?s in selection, which will be replaced by the values from
selectionArgs selectionArgs, in order that they appear in the selection. The values will be
bound as Strings.
groupBy

A filter declaring how to group rows, formatted as an SQL GROUP BY


clause (excluding the GROUP BY itself). Passing null will cause the rows to
not be grouped.

having

A filter declare which row groups to include in the cursor, if row grouping is
being used, formatted as an SQL HAVING clause (excluding the HAVING
itself). Passing null will cause all row groups to be included, and is required
when row grouping is not being used.

orderBy

How to order the rows, formatted as an SQL ORDER BY clause (excluding


the ORDER BY itself). Passing null will use the default sort order, which
may be unordered.
66

DONG NAI UNIVERSITY OF TECHNOLOGY

4.5 Querying SQLite

67

DONG NAI UNIVERSITY OF TECHNOLOGY

4.6 Simple Database Demo

Transactiontake yourself
SQLiteOpenHelpertake yoursel

68

DONG NAI UNIVERSITY OF TECHNOLOGY

5. Content Provider
5.1 Introduction
5.2 Using common Content Provider
5.3 Create your own Content Provider

69

DONG NAI UNIVERSITY OF TECHNOLOGY

5.1 Introduction
content provider is a specialized type of
data store that exposes standardized ways
to retrieve and manipulate the stored data.
You wish to share data between
applications, you need to use the content
provider model as recommended in
Android.
most useful built-in content providers

70

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content Provider


To query a content provider, you provide a query string in
the form of a URI, with an optional specifier for a particular
row, using the following syntax:
<standard_prefix>://<authority>/<data_path>/<id>
For example, to retrieve all the bookmarks stored by your
web browsers (in Android), you would use the following
content URI:
content://browser/bookmarks
To retrieve all the contacts stored by the Contacts application,
the URI would look like this:
content://contacts/people
To retrieve a particular contact, you can specify the URI with
a specific ID:
content://contacts/people/3
71

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content Provider


Retrieves a managed cursor
CursorLoader loader=new
CursorLoader(context, uri, null, null, null, null);
Cursor c=loader.loadInBackground();
Is equivalent to:
Cursor c = getContentResolver()
.query(uri, null, null, null, null);
getContentResolver() method returns a ContentResolver
object, which helps to resolve a content URI with the
appropriate content provider
Parametres: URI, projection, SQLWHERE, ORDERBY

72

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content ProviderGet contacts:

73

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content ProviderGet contacts:

Or using getContentResolver instead CursorLoader:

74

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content ProviderAccess Call Log:

75

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content ProviderAccess Call Log:

Similar the Contact, you could


use CursorLoader class to
access the call log

76

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content Provider


Access Media Store:

77

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content Provider


Access Media Store:

Similar another provider, you


could use getContentResolver to
access the Media

78

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content Provider


Access Book mark:

79

DONG NAI UNIVERSITY OF TECHNOLOGY

5.2 Using common Content Provider


Access Book mark:

80

DONG NAI UNIVERSITY OF TECHNOLOGY

5.3 Create your own Content Provider


extend the abstract ContentProvider class and override
the various methods defined within it.
The 6 methods you need to implement are:
getType(): Returns the MIME type of the data at the given
URI.
onCreate(): Called when the provider is being started.
query(): Receives a request from a client. The result is
returned as a Cursor object.
insert(): Inserts a new record into the content provider.
delete(): Deletes an existing record from the content provider.
update(): Updates an existing record from the content provider.

Within your content provider, you may choose to store


your data however you like: traditional file system, XML,
database, or even through web services
81

DONG NAI UNIVERSITY OF TECHNOLOGY

5.3 Create your own Content Provider


Declare the Constant Content Provider
Values:
Declare
Provider in Manifest file:
<provider name=".MyProvider"
authorities="abc.com.MyProvider" . . >
Declare Content URI and Path:
Example
public static final String AUTHORITY = "abc.com.MyProvider";
// Same as Androidmanifest.xml entry
public static final String CONTENT_URI =
"content://"+ AUTHORITY + "/demodb");
//URI for access the Content Provider
Using UriMatcher:
The UriMatcher class is a helper class for pattern matching on
the URIs that are passed to this content provider.
82

DONG NAI UNIVERSITY OF TECHNOLOGY

5.3 Create your own Content Provider

Example to understand this


technical

Create a Project with name


LearnCreateOwnContentPro
vider

83

DONG NAI UNIVERSITY OF TECHNOLOGY

DatabaseHelper class
5.3 Create your own Content Provider

84

DONG NAI UNIVERSITY OF TECHNOLOGY

Movie class
5.3 Create your own Content Provider

85

DONG NAI UNIVERSITY OF TECHNOLOGY

Movie class
5.3 Create your own Content Provider

86

DONG NAI UNIVERSITY OF TECHNOLOGY

Movie class
5.3 Create your own Content Provider

87

DONG NAI UNIVERSITY OF TECHNOLOGY

MyContentProvider cla
5.3 Create your own Content Provider

88

DONG NAI UNIVERSITY OF TECHNOLOGY

MyContentProvider cla
5.3 Create your own Content Provider

89

DONG NAI UNIVERSITY OF TECHNOLOGY

MyContentProvider cla
5.3 Create your own Content Provider

90

DONG NAI UNIVERSITY OF TECHNOLOGY

MainActivity XML
5.3 Create your own Content Provider

91

DONG NAI UNIVERSITY OF TECHNOLOGY

MainActivity class
5.3 Create your own Content Provider

92

DONG NAI UNIVERSITY OF TECHNOLOGY

MainActivity class
5.3 Create your own Content Provider

93

DONG NAI UNIVERSITY OF TECHNOLOGY

MainActivity class
5.3 Create your own Content Provider

94

DONG NAI UNIVERSITY OF TECHNOLOGY

MainActivity class
5.3 Create your own Content Provider

95

DONG NAI UNIVERSITY OF TECHNOLOGY

MainActivity class
5.3 Create your own Content Provider

96

DONG NAI UNIVERSITY OF TECHNOLOGY

Manifest XML
5.3 Create your own Content Provider

97

DONG NAI UNIVERSITY OF TECHNOLOGY

END
98

You might also like