Friday, November 21, 2014

Coursera (Week 8) DataManagement , Content Providers, and Services

DataManagement

https://class.coursera.org/android-002/lecture/91

Manage data across multiple application sessions

SharedPreferences class - small primitive data i.e. username, account name, user customizations
- persistent Map : key value pairs of simple data types
- automatically persisted across application sessions
- long term storage of customizable application data
- to get SharedPreferences class within an activity,  use Activity.getPreferences (int accessmode) - example of mode is MODE_PRIVATE
to get SharedPreferences class NOT within an activity,  use Context.getSharedPreferences(String name, in accessmode) - name example could be name of shared preferences file
- after saving object, can edit file using SharedPreferences.edit() method returns SharedPreferences.editor instance - putInt(key,value), putString(key,value), remove(key)
- SharedPreferences.editor.commit() to persist
- read it later SharedPreference object - getAll(),  getBoolean(key) , getString(key)

DataManagementSharedpreferences app

File - storage area internal (smaller, application private data sets) or
external (larger non private)
Internal device storage - medium amount data private  i.e. temp files
External device storage - large amount non private i.e. songs, pictures

File API - FileOutputStream - openFileOutput(String name, int mode)
- open private file for writing
FileInputStream
- openFileInput() for reading
DataManagementFileInternalMemory app
- see if its exists, otherwise opens it, writes text to it, reads text, displays its
http://developer.android.com/reference/android/content/Context.html
Context.openFileOuput method() - passed in an integer, Context.MODE_PRIVATE: only be accessed by applications sharing the same user ID as the calling application


databases - private structured data Complex SQL Lite databases


https://class.coursera.org/android-002/lecture/93

External memory - removable such as sdk card, appear or disappera without warning, first determine state of external emmory
Environment.getExternalStorageState()
- MEDIA_MOUNTED
-MEDIA_MOUNTED_READ_ONLY
-MEDIA_REMOVED - NOT PRESENT

WRITE_EXTERNAL_STORAGE permission

DataManagementFileExternalMemory app




Cache files - temp files, cache directories, may be deleted when storage is low
Context.getCacheDir()
Context.getExternalCacheDir()

SQLite
- in memory relational database with small footprint
<300KB
ACID

SqliteOpenHelper class
call super() from sublclass
override OnCreate() and onUpgrade()

DataManagementSql app
-DatabaseOpenHelper extends SQLiteOpenHelper
- android.database.Cursor

ContentValues values = new ContentValues(); values.put(DatabaseOpenHelper.ARTIST_NAME, "Frank Sinatra"); mDbHelper.getWritableDatabase().insert(DatabaseOpenHelper.TABLE_NAME, null, values); values.clear();

ContentValues values = new ContentValues();
values.put(DatabaseOpenHelper.ARTIST_NAME, "Johnny Cash");     mDbHelper.getWritableDatabase().update(DatabaseOpenHelper.TABLE_NAME, values, DatabaseOpenHelper.ARTIST_NAME + "=?", new String[] { "Jawny Cash" });

/data/data/<package_name/databases

emulator terminal:
# adb -s  emulator-port# shell

#sqlite3 /data/data/course.examples.DataManagement.DataBaseExample/databases/artist_dbd

#sqllite3 -help


ContentProviders

https://class.coursera.org/android-002/lecture/87

https://class.coursera.org/android-002/lecture/89

http://developer.android.com/guide/topics/providers/content-providers.html

Fundamental component android : content providers - centralized repos of structured data
data to be shared across multiple app - inter-application data sharing
ContentResolver class
- databae style interfaxe for read write data
- notifies addtl services such as notify when data changed
Context.getContentResolver()

Code running in one process access data in another process

standard content providers
Browser
Call Log
contacts
media
user dictionary
Represented as database table

Use URI - content providers referenced by URI

content:://Authority/Path/id
- content: scheme indicating data that is managed by content provider
- authority: id for content provider
-path: 0 or more segments indicating type of data accessed
-id : optional is specific record within dataset

example content://com.android.contacts/contacts

following classes applications use to identify and access a ContentProvider:
- ContentResolver, URI

ContentResolver.query()

query returns a cursor, has input parms such as URI, columns , selection pattern, pattern args, and sort order

ContentProviderWithCursorAdapter app

- contacts provider and photo
- columns specified
- ContentResolver class reference
-query string pattern
- sort order
- query which returns cursor
ContactsInfoListAdapter
-bindView method fills in view

CursorLoader - can take while to complete, avoid intensive operation
this class uses async task so its done on background thread
LoaderCallbacks interface
initLoader() - init and activate loader

callback onCreateLoader()
callback onLoadFinished()
callback onLoaderReset - previous loader reset

ContentProviderWithCursorLoader app
- getLoaderManager().initLoader(0,null,this) - this callback

onCreateLoader() method -  query returns new CursorLoader

onLoadFinished() - swap new cursor that is passed in into List adapter
OnLoaderReset() - called when last cursor to finished method is about to be closed

ContentResover.delete

uri, sql pattern, pattern args

ContentResover.insert
uri , parms

ContentResover.update
uri
new field values, pattern

ContentProviders/ContactsListInsertContacts  app

mAccountList = AccountManager.get(this).getAccountsByType("com.google");
-permission  android.permission.GET_ACCOUNTS


getContentResolver.applyBatch - does inserts all at once

Create content provider -

Implement storage system
Define a Contract class
ContentProvider subclass with insert,delete, etc
Declare it in manifest file

ContentProviderCustom app
- StringsContentProvider class
- delete method
- DataRecord object
-query method with MatrixCursor

manifest file is a provider tag
- exported to true

ContentProviderCustomUser app


Services

https://class.coursera.org/android-002/lecture/83
https://class.coursera.org/android-002/lecture/85

Service class

Fundamental component - long running processes

work in background, one process interact with another process

remote method execution

starting it:
Conext.startService(Intent)
run in background indefinately
perform single operation, and dont transfer results
by default run on main thread
Context.bindService()
 - allows component to send requests and receive responses from a local or remote service
at binding time, start service if not started already. will run as long as one client connected
LoggingServiceClient


MusicPlayingServiceExample



No comments:

Post a Comment