3 - xử lý tập tin, lưu trạng thái Ứng dụng, thao tác cơ sở dữ liệu và content...

98
DONG NAI UNIVERSITY OF TECHNOLOGY 1 5. Content Provider 4. SQLite 3. Shared Preferences 2. XML Parser 1. Files

Upload: nguyenduchoang

Post on 24-Sep-2015

222 views

Category:

Documents


0 download

DESCRIPTION

Xử Lý Tập Tin, Lưu Trạng Thái Ứng Dụng, Thao Tác Cơ Sở Dữ Liệu Và Content Provider

TRANSCRIPT

PowerPoint Presentation

15. Content Provider4. SQLite3. Shared Preferences2. XML Parser1. FilesDONG NAI UNIVERSITY OF TECHNOLOGY12 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.Android FilesDONG NAI UNIVERSITY OF TECHNOLOGY3Data 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 TECHNOLOGY41. Files1.1 Internal Storage1.2 External Storage1.3 Saving Cache filesDONG NAI UNIVERSITY OF TECHNOLOGY51.1 Internal StorageReading 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 TECHNOLOGY61.1 Internal StorageReading Resource File

DONG NAI UNIVERSITY OF TECHNOLOGY71.1 Internal StorageIf 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 TECHNOLOGY81.1 Internal Storage

Reading an internal FileDONG NAI UNIVERSITY OF TECHNOLOGY91.1 Internal StorageWriting an internal File

DONG NAI UNIVERSITY OF TECHNOLOGY101.2 External StorageReading/Writing to External Devices SD card. SD card has the obvious advantage of a larger working space.

DONG NAI UNIVERSITY OF TECHNOLOGY111.2 External Storage

ReadingDONG NAI UNIVERSITY OF TECHNOLOGY11121.2 External StorageWriting

DONG NAI UNIVERSITY OF TECHNOLOGY12131.3 Saving Cache filesTo 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 fileDONG NAI UNIVERSITY OF TECHNOLOGY141.3 Saving Cache filesIf 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.DONG NAI UNIVERSITY OF TECHNOLOGY151.3 Saving Cache files

Creating cache fileDONG NAI UNIVERSITY OF TECHNOLOGY161.3 Saving Cache filesReading cache file

DONG NAI UNIVERSITY OF TECHNOLOGY171.3 Saving Cache filesGet all cache files

DONG NAI UNIVERSITY OF TECHNOLOGY182. XML Parser2.1 Whats XML?2.2 How is XML used?2.3 Parsing XML by DOM2.4 Parsing XML by SAXDONG NAI UNIVERSITY OF TECHNOLOGY192.1 Whats XML?Extensible Markup Language (XML) is a set of rules for encoding documents in a readable form. Similar to HTML but 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. DONG NAI UNIVERSITY OF TECHNOLOGY202.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 ... 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. DONG NAI UNIVERSITY OF TECHNOLOGY212.2 How is XML used?

DONG NAI UNIVERSITY OF TECHNOLOGY222.3 Parsing XML by DOMDOM : W3C DocumentBuilder ParserDocument Object Model Cache all Standard tree structure

Parsing this XML

DONG NAI UNIVERSITY OF TECHNOLOGY232.3 Parsing XML by DOMThe XML file is given to the W3C parser to construct an equivalent tree. Elements from the XML file are represented in the parse-tree 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(), DONG NAI UNIVERSITY OF TECHNOLOGY242.3 Parsing XML by DOMCreating a Java DOM XML parser is done using the javax.xml.parsers.DocumentBuilderFactory class. Parsing an XML file into a DOM tree

DONG NAI UNIVERSITY OF TECHNOLOGY252.3 Parsing XML by DOM

DONG NAI UNIVERSITY OF TECHNOLOGY262.3 Parsing XML by DOMThe 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();

DONG NAI UNIVERSITY OF TECHNOLOGY272.4 Parsing XML by SAXSAX Simple API for XML scan the document Less memory Faster Complex

Parsing this XML

DONG NAI UNIVERSITY OF TECHNOLOGY282.4 Parsing XML by SAXA 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. DONG NAI UNIVERSITY OF TECHNOLOGY292.4 Parsing XML by SAXAttributes from an element can be extracted using the methods: .getAttributeCount() .getAttributeName() .getAttributeValue()

DONG NAI UNIVERSITY OF TECHNOLOGY302.4 Parsing XML by SAXUsing the XmlPullParser class to generate scanner/parser to traverse an XML document

DONG NAI UNIVERSITY OF TECHNOLOGY312.4 Parsing XML by SAX

DONG NAI UNIVERSITY OF TECHNOLOGY322.4 Parsing XML by SAX

DONG NAI UNIVERSITY OF TECHNOLOGY332.4 Parsing XML by SAX

DONG NAI UNIVERSITY OF TECHNOLOGY343. Shared Preferences3.4 Activity and Framework Preferences3.1 Creating and Saving Preferences3.2 Saving and Restoring Instance State3.3 Shared Preference Change ListenersDONG NAI UNIVERSITY OF TECHNOLOGY353.1 Creating and Saving PreferencesTo 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.DONG NAI UNIVERSITY OF TECHNOLOGY363.1 Creating and Saving Preferences

Checked and then click LoginRe open application information are restoredDONG NAI UNIVERSITY OF TECHNOLOGY373.1 Creating and Saving Preferences

DONG NAI UNIVERSITY OF TECHNOLOGY383.1 Creating and Saving Preferences

DONG NAI UNIVERSITY OF TECHNOLOGY393.1 Creating and Saving Preferences

DONG NAI UNIVERSITY OF TECHNOLOGY403.1 Creating and Saving Preferences

The saving location of PreferencesXML formatDONG NAI UNIVERSITY OF TECHNOLOGY413.2 Saving and Restoring Instance StateIf 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.DONG NAI UNIVERSITY OF TECHNOLOGY423.2 Saving and Restoring Instance State

DONG NAI UNIVERSITY OF TECHNOLOGY433.2 Saving and Restoring Instance StateTo 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 handlerDONG NAI UNIVERSITY OF TECHNOLOGY443.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.DONG NAI UNIVERSITY OF TECHNOLOGY453.3 Shared Preference Change ListenersThe 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.DONG NAI UNIVERSITY OF TECHNOLOGY463.3 Shared Preference Change Listeners

DONG NAI UNIVERSITY OF TECHNOLOGY473.4 Activity and Framework PreferencesAndroid 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.DONG NAI UNIVERSITY OF TECHNOLOGY483.4 Activity and Framework Preferences

1. Create Preference LayoutDONG NAI UNIVERSITY OF TECHNOLOGY493.4 Activity and Framework Preferences

The preference Layout will be stored in res/xml folder1. Create Preference Layout

DONG NAI UNIVERSITY OF TECHNOLOGY503.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.DONG NAI UNIVERSITY OF TECHNOLOGY513.4 Activity and Framework Preferences2. Create Activity for Preference LayoutExtends from PreferenceActivity class

3. Config manifest xml

DONG NAI UNIVERSITY OF TECHNOLOGY523.4 Activity and Framework Preferences

4. Modify MainActivityDONG NAI UNIVERSITY OF TECHNOLOGY533.4 Activity and Framework Preferences

MainActivitySettingActivitySettingActivityInformation get from MainActivityDONG NAI UNIVERSITY OF TECHNOLOGY544. SQLite4.1 Introduction4.2 Creating Database4.3 Creating Table4.4 Action Query:Insert, Update, Delete4.5 Querying SQLite4.6 Simple Database DemoDONG NAI UNIVERSITY OF TECHNOLOGY554.1 IntroductionEmbedded 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.DONG NAI UNIVERSITY OF TECHNOLOGY564.2 Creating DatabaseThe simplest way to create a new SQLiteDatabase instance for your application is to use the openOrCreateDatabase() method of your application Contextimport android.database.sqlite.SQLiteDatabase;

DONG NAI UNIVERSITY OF TECHNOLOGY574.2 Creating Database

Storing Database directory:/data/data/app/databases/So, in this case, the path to the database would be:DONG NAI UNIVERSITY OF TECHNOLOGY584.2 Creating Database Beware of sharing issues. You cannot access internaldatabases belonging to other people (instead use ContentProviders or external SD resident DBs). An SD resident database requires the Manifest to include:

DONG NAI UNIVERSITY OF TECHNOLOGY594.3 Creating Table

DONG NAI UNIVERSITY OF TECHNOLOGY604.4 Action Query:Insert, Update, DeleteInserting Records: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.

DONG NAI UNIVERSITY OF TECHNOLOGY614.4 Action Query:Insert, Update, DeleteUpdating Records:You can modify records in the database using the update() method.The update() method takes four arguments:The table to update recordsA ContentValues object with the modified fields to updateAn optional WHERE clause, in which ? identifies a WHERE clause argumentAn array of WHERE clause arguments, each of which is substituted in place of the ?s from the second parameterpublic int update (String table, ContentValues values, String whereClause, String[] whereArgs) This method Returns the number of rows affected DONG NAI UNIVERSITY OF TECHNOLOGY624.4 Action Query:Insert, Update, DeleteUpdating Records:

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.DONG NAI UNIVERSITY OF TECHNOLOGY634.4 Action Query:Insert, Update, DeleteDeleting Records:You can remove records from the database using the remove() method.The remove() method takes 3 arguments:The table to delete the record fromAn optional WHERE clause, in which ? identifies a WHERE clause argumentAn array of WHERE clause arguments, each of which is substituted in place of the ?s from the second parameterPassing 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 DONG NAI UNIVERSITY OF TECHNOLOGY644.4 Action Query:Insert, Update, DeleteDeleting Records:

Delete all rows in table tblop:Delete row with malop=dhth7c:

delete method will return the number of rows affected DONG NAI UNIVERSITY OF TECHNOLOGY654.5 Querying SQLiteWhen 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) ReturnsA Cursor object, which is positioned before the first entry. Note that Cursors are not synchronizedDONG NAI UNIVERSITY OF TECHNOLOGY664.5 Querying SQLitetable 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.selectionArgs You may include ?s in selection, which will be replaced by the values from 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.DONG NAI UNIVERSITY OF TECHNOLOGY674.5 Querying SQLite

DONG NAI UNIVERSITY OF TECHNOLOGY684.6 Simple Database Demo

Transactiontake yourselfSQLiteOpenHelpertake yourselfDONG NAI UNIVERSITY OF TECHNOLOGY695. Content Provider5.1 Introduction5.2 Using common Content Provider5.3 Create your own Content ProviderDONG NAI UNIVERSITY OF TECHNOLOGY705.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 providersDONG NAI UNIVERSITY OF TECHNOLOGY715.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: :////For example, to retrieve all the bookmarks stored by your web browsers (in Android), you would use the following content URI:content://browser/bookmarksTo 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/3DONG NAI UNIVERSITY OF TECHNOLOGY725.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, ORDERBYDONG NAI UNIVERSITY OF TECHNOLOGY735.2 Using common Content Provider Get contacts:

DONG NAI UNIVERSITY OF TECHNOLOGY

745.2 Using common Content Provider Get contacts:

Or using getContentResolver instead CursorLoader:

DONG NAI UNIVERSITY OF TECHNOLOGY74755.2 Using common Content Provider Access Call Log:

DONG NAI UNIVERSITY OF TECHNOLOGY75765.2 Using common Content Provider Access Call Log:

Similar the Contact, you could use CursorLoader class to access the call logDONG NAI UNIVERSITY OF TECHNOLOGY76775.2 Using common Content Provider Access Media Store:

DONG NAI UNIVERSITY OF TECHNOLOGY77785.2 Using common Content Provider Access Media Store:

Similar another provider, you could use getContentResolver to access the MediaDONG NAI UNIVERSITY OF TECHNOLOGY78795.2 Using common Content Provider Access Book mark:

DONG NAI UNIVERSITY OF TECHNOLOGY79805.2 Using common Content Provider Access Book mark:

DONG NAI UNIVERSITY OF TECHNOLOGY80815.3 Create your own Content Provider extend the abstract ContentProvider class and overridethe 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 storeyour data however you like: traditional file system, XML,database, or even through web servicesDONG NAI UNIVERSITY OF TECHNOLOGY825.3 Create your own Content ProviderDeclare Provider in Manifest file: Declare Content URI and Path:Examplepublic static final String AUTHORITY = "abc.com.MyProvider"; // Same as Androidmanifest.xml entrypublic static final String CONTENT_URI ="content://"+ AUTHORITY + "/demodb"); //URI for access the Content ProviderUsing UriMatcher: The UriMatcher class is a helper class for pattern matching on the URIs that are passed to this content provider.Declare the Constant Content Provider Values:DONG NAI UNIVERSITY OF TECHNOLOGY835.3 Create your own Content Provider

Create a Project with name LearnCreateOwnContentProvider

Example to understand this technicalDONG NAI UNIVERSITY OF TECHNOLOGY845.3 Create your own Content Provider

DatabaseHelper classDONG NAI UNIVERSITY OF TECHNOLOGY855.3 Create your own Content Provider

Movie classDONG NAI UNIVERSITY OF TECHNOLOGY865.3 Create your own Content ProviderMovie class

DONG NAI UNIVERSITY OF TECHNOLOGY875.3 Create your own Content ProviderMovie class

DONG NAI UNIVERSITY OF TECHNOLOGY885.3 Create your own Content ProviderMyContentProvider class

DONG NAI UNIVERSITY OF TECHNOLOGY895.3 Create your own Content ProviderMyContentProvider class

DONG NAI UNIVERSITY OF TECHNOLOGY905.3 Create your own Content ProviderMyContentProvider class

DONG NAI UNIVERSITY OF TECHNOLOGY915.3 Create your own Content ProviderMainActivity XML

DONG NAI UNIVERSITY OF TECHNOLOGY925.3 Create your own Content ProviderMainActivity class

DONG NAI UNIVERSITY OF TECHNOLOGY935.3 Create your own Content ProviderMainActivity class

DONG NAI UNIVERSITY OF TECHNOLOGY945.3 Create your own Content ProviderMainActivity class

DONG NAI UNIVERSITY OF TECHNOLOGY955.3 Create your own Content ProviderMainActivity class

DONG NAI UNIVERSITY OF TECHNOLOGY965.3 Create your own Content ProviderMainActivity class

DONG NAI UNIVERSITY OF TECHNOLOGY975.3 Create your own Content ProviderManifest XML

DONG NAI UNIVERSITY OF TECHNOLOGY

END98DONG NAI UNIVERSITY OF TECHNOLOGY