1 / 59

Android Fundamentals

Android Fundamentals. Mobile Application Development Selected Topics – CPIT 490. Data Storage. Data Storage Shared Preferences (a lightweight mechanism) Data Files SQLite Content Provider Saving Data Your options (most complex apps use all)

rosehenry
Download Presentation

Android Fundamentals

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Android Fundamentals Mobile Application Development Selected Topics – CPIT 490

  2. Data Storage • Data Storage • Shared Preferences (a lightweight mechanism) • Data Files • SQLite • Content Provider • Saving Data • Your options (most complex apps use all) • Shared Preferences (just to store name-value pair like name, DOB, etc) • Bundles • Local files (to store ad-hoc data like RSS feed, note-taking, etc); External storage (if you need to share data with other applications) • Local database (SQLite) • Remote database • Saving data is obviously essential

  3. Saving UI State • Activity should save its user interface state each time it moves to the background • Required due to OS killing processes • Even if you think your app will be in the foreground all the time, you need to do this, because of.... • Phone calls • Other apps • The nature of mobile use

  4. Shared Preferences • Simple, lightweight key/value pair (or name/value pair NVP) mechanism • Support primitive types: Boolean, string, float, long and integer • Stored as XML in the protected application directory on main memory (/data/data/<package name>/shared_prefs/<package name>_preferences.xml) • Shared among application components running in the same application context • //Getting Context example • public class MyActivity extends Activity { • public void method() { • Context actContext = this; // since Activity extends Context • Context appContext = getApplicationContext(); • Context vwContext = ((Button)findViewById(R.id.btn_id)).getContext(); • } • }

  5. DDMS – File Explorer • http://developer.android.com/guide/developing/debugging/ddms.html • (Window > Open Perspective > Other... > DDMS)

  6. Creating and Sharing Prefs • public static String MY_PREFS = "<package_name>_preferences"; • int mode = Activity.MODE_PRIVATE; • SharedPreferencesmySharedPreferences = • getSharedPreferences(MY_PREFS, mode); • SharedPreferences.Editor editor = mySharedPreferences.edit(); • // Store new primitive types in the shared preferences object. • editor.putBoolean("isTrue", true); • editor.putFloat("lastFloat", 1f); • editor.putInt("wholeNumber", 2); • editor.putLong("aNumber", 3l); • editor.putString("textEntryValue", "Not Empty"); • // Commit the changes. • editor.commit();

  7. Retrieving Prefs • public static String MY_PREFS = "MY_PREFS"; • public void loadPreferences() { • // Get the stored preferences • int mode = Activity.MODE_PRIVATE; • SharedPreferencesmySharedPreferences = getSharedPreferences(MY_PREFS, mode); • // Retrieve the saved values. • booleanisTrue = mySharedPreferences.getBoolean("isTrue", false); • float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f); • intwholeNumber = mySharedPreferences.getInt("wholeNumber", 1); • long aNumber = mySharedPreferences.getLong("aNumber", 0); • String stringPreference = • mySharedPreferences.getString("textEntryValue", ""); • }

  8. Preference Activity • System-style preference screens • Familiar • Can merge settings from other apps (e.g., system settings such as location) • 3 parts • Preference Screen Layout (XML) • Extension of PreferenceActivity • onSharedPreferenceChangeListener

  9. Shared Preferences • Create an xml file to indicate what to store • <PreferenceScreenxmlns:android=”http://schemas.android.com/apk/res/android”> • <PreferenceCategoryandroid:title=”Category 1”> • Provide the key for different preferences • <CheckBoxPreference … android:key=”checkboxPref” /> • Create an activity that extends the PreferenceActivity base class, and then call the addPreferencesFromResource() method to load the XML file containing the preferences: addPreferencesFromResource(R.xml.myapppreferences); • The MODE_PRIVATE constant indicates that the preference file can only be opened by the application that created it • Use getString() method to retrieve string preferences and use putString() method to update string preferences • Change the default preference (net.learn2develop • .<packagename>_preferences.xml> using PreferenceManagerprefMgr = getPreferenceManager(); prefMgr.setSharedPreferencesName(“appPreferences”);

  10. Preference Activity • XML • <?xml version="1.0" encoding="utf-8"?> • <PreferenceScreenxmlns:android="http://schemas.android.com/apk/res/android"> • <PreferenceCategoryandroid:title="My Preference Category"/> • <CheckBoxPreference • android:key="PREF_CHECK_BOX" • android:title="Check Box Preference" • android:summary="Check Box Preference Description" • android:defaultValue="true" • /> • </PreferenceCategory> • </PreferenceScreen>

  11. Preference Activity • Options • CheckBoxPreference • EditTextPreference • ListPreference • RingtonePreference

  12. Preference Activity Public class MyPreferenceActivity extends PreferenceActivity { @Override Public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } In manifest... <activity android:name=“.MyPreferenceActivity” android:label=“My Preferences”> To start... Intent I = new Intent(this, MyPreferenceActivity.class); startActivityForResult(i, SHOW_PREFERENCES);

  13. Using Prefs from Pref. Activity • Recorded shared prefs are stored in Application Context. Therefore, available to any component: • Activities • Services • BroadcastReceiver • Context context = getApplicationContext(); • SharedPreferencesprefs = • PreferenceManager.getDefaultSharedPreferences(context); • // then Retrieve values using get<type> method

  14. Prefs change listeners • Run some code whenever a Shared Preference value is added, removed, modified • Useful for Activities or Services that use SP framework to set application preferences

  15. SP change listeners • public class MyActivity extends Activity implements • OnSharedPreferenceChangeListener { • @Override • public void onCreate(Bundle SavedInstanceState) { • // Register this OnSharedPreferenceChangeListener • Context context = getApplicationContext(); • SharedPreferencesprefs = • PreferenceManager.getDefaultSharedPreferences(context); • prefs.registerOnSharedPreferenceChangeListener(this); • } • public void onSharedPreferenceChanged(SharedPreferencesprefs, • String key) { • // TODO Check the shared preference and key parameters • // and change UI or behavior as appropriate. • } • }

  16. Shared Preferences – Summary • Lightweight key-value pair storage • General framework that allows you to save and retrieve persistent key-value pairs of primitive data types. • Use it to save any primitive data: booleans, floats, ints, longs, and strings. • Persist amongst user sessions • getSharedPreferences() – Use this if you need multiple preferences files identified by name where you specify with the first parameter • getPreferences() – Use this if you need only one preferences file for your Activity. Since this will be the only preferences file for your Activity, you don’t supply a name • Get a SharedPreferences.Editor • Call edit() • Add values with methods (put<type>()) • Commit new values with commit() • Use SharedPreferences methods (get<type>()) to grab the values from your preferences • Example: getBoolean(key, defaultvalue);

  17. Bundles • Activities offer onSaveInstanceState handler • Works like SharedPreferences • Bundle parameter represents key/value map of primitive types that can be used save the Activity’s instance values • Bundle made available as a parameter passed in to the onCreate and onRestoreInstance method handlers • Bundle stores info needed to recreate UI state

  18. Saving Bundle @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putBoolean("MyBoolean", true); savedInstanceState.putDouble("myDouble", 1.9); savedInstanceState.putInt("MyInt", 1); savedInstanceState.putString("MyString", "Welcome back to Android"); // etc. super.onSaveInstanceState(savedInstanceState); }

  19. Restoring Bundle • @Override • public void onRestoreInstanceState(Bundle savedInstanceState) { • super.onRestoreInstanceState(savedInstanceState); • // Restore UI state from the savedInstanceState. • // This bundle has also been passed to onCreate. • booleanmyBoolean = savedInstanceState.getBoolean("MyBoolean"); • double myDouble = savedInstanceState.getDouble("myDouble"); • intmyInt = savedInstanceState.getInt("MyInt"); • String myString = savedInstanceState.getString("MyString"); • }

  20. Saving/loading files • Biggest decision: location • Local vs Remote • Internal vs External • When you create a new AVD, you can emulate the existence of an SD card. Simply enter the size of the SD card that you want to emulate • Alternatively, you can simulate the presence of an SD card in the Android emulator by creating a disk image first and then attaching it to the AVD. The mksdcard.exe utility (located in the tools folder of the Android SDK) enables you to create an ISO disk image • Code is standard Java • String FILE_NAME = "tempfile.tmp"; • // Create a new output file stream that’s private to this application. • FileOutputStreamfos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE); • // Open input file stream. • FileInputStreamfis = openFileInput(FILE_NAME);

  21. Saving/loading files • // MODE_WORLD_READABLE constant means that the file is only readable • FileOutputStreamfOut = openFileOutput(“textfile.txt”, MODE_WORLD_READABLE); • MODE_PRIVATE (the file can only be accessed by the application that created it), MODE_APPEND (for appending to an existing file), and MODE_WORLD_WRITEABLE (all other applications have write access to the file). • Convert a character stream into a byte stream • OutputStreamWriterosw = new OutputStreamWriter(fOut); • Use write() to write to a file: osw.write(str); • To ensure everything is written to the file: osw.flush(); • Close the file using: osw.close();

  22. Saving/loading files • Read the file: FileInputStream fIn = openFileInput(“textfile.txt”); • InputStreamReader isr = new InputStreamReader(fIn); • To read from the file: char[] inputBuffer = new char[100]; String s = “”; int charRead; while ((charRead = isr.read(inputBuffer))>0) { //---convert the chars to a String--- String readString = String.copyValueOf(inputBuffer, 0, charRead); s += readString; inputBuffer = new char[100]; } • Using DDMS (under File Explorer) in Eclipse, we could see /data/data/net.learn2develop.Files/files • To copy a file from emulator or device to computer: adb pull <source path on emulator> • To upload a file to emulator or device: adb push <filename> <destination path on emulator> • To modify file permissions: adb shell and chmod

  23. Saving/Loading files • Can only write in current application folder ( /data/data/<package_name>/files/<filename>) or external storage (e.g., /mnt/sdcard/<filename>) • Exception thrown otherwise • For external, must be careful about availability of storage card • Behavior when docked • Cards get wiped • SD Card Writing Permission (AndroidManifest.xml) • <uses-permission • android:name= "android.permission.WRITE_EXTERNAL_STORAGE"> • </uses-permission>

  24. Check SD card private static final String ERR_SD_MISSING_MSG = “ERRSD cannot see your SD card. Please reinstall it and do not remove it."; private static final String ERR_SD_UNREADABLE_MSG = "CITY cannot read your SD (memory) card. This is probably because your phone is plugged into your computer. Please unplug it and try again."; public static String getSDCard() throws ERRSDException { if (Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)) throw new ERRSDException(ERR_SD_MISSING_MSG); else if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) throw new ERRSDException(ERR_SD_UNREADABLE_MSG); File sdCard = Environment.getExternalStorageDirectory(); // “/mnt/sdcard” if (!sdCard.exists()) throw new ERRSDException(ERR_SD_MISSING_MSG); if (!sdCard.canRead()) //for writing sdCard.canWrite() throw new ERRSDException(ERR_SD_UNREADABLE_MSG); return sdCard.toString(); }

  25. SD Card storage • getExternalStorageDirectory() method is used to get the full path to the external storage • returns the “/sdcard” path for a real device, and “/mnt/sdcard” for an Android emulator • Don’t hardcode the path of the SD card as different manufacturers can assign different path for the SD card

  26. Static Resources • You could add files to your package during design time • This is done in res/raw folder • Use the getResources() method (of the Activity class) to return a Resources object, and then use its openRawResource() method to open the file contained in the res/raw folder • InputStream is = this.getResources().openRawResource(R.raw.textfile); • BufferedReaderbr = new BufferedReader(new InputStreamReader(is)); • String str = null; • try { • while ((str = br.readLine()) != null) { • Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show(); • } • is.close(); br.close(); • } catch (IOException e) { e.printStackTrace(); }

  27. SQLite • Embedded database for Android • Supports 3 main data types • TEXT (like Java String), INTEGER (like Java long), REAL (like Java double) • No type checking inherent in SQLite. SQLite does not verify that the type written to each cell is of the defined type • Each DB is private to Application that created it • Data is stored at: • /data/data/<package name>/databases/<db name> • Documentation on SQLITE available at: http://www.sqlite.org/sqlite.html • Good GUI tool for SQLITE available at: http://sqliteadmin.orbmu2k.de/ • SQL and SQLite Language Syntax at: http://www.sqlite.org/lang.html

  28. Using SQLite • Use a helper class called DBAdapter that creates, opens, closes, and uses a SQLite database • Create a subclass of SQLiteOpenHelper • Override at least onCreate() - where you can create tables • Can also override onUpgrade() - make a modification to the tables structures • Call getWritableDatabase() to get read/write instance of SQLiteDatabase • Can then call insert(), delete(), update() • execSQL(String sql, [Object[] bindArgs]) – executes the SQL directly (not a SELECT/INSERT/UPDATE/DELETE) • rawQuery(String sql, String[] selectionArgs) – runs provided SQL and returns a Cursor over result set • query() – has many different parameters but returns a Cursor over result set • If you want to e.g. CREATE TABLE that does not return values you can use execSQL(), if you want a Cursor as result use rawQuery() (=SELECT statements). • If you want to execute something in database without concerning its output (e.g create/alter tables), then use execSQL, but if you are expecting some results in return against your query (e.g. select records) then use rawQuery

  29. Subclass SQLiteOpenHelper • public class DatabaseHelper extends SQLiteOpenHelper { • static final String dbName= "demoDB" ; • static final intdbVersion= 1 ; • static final String employeeTable= "Employees" ; • static final String colID= "EmployeeID" ; • static final String colName= "EmployeeName" ; • static final String colAge= "Age" ; • static final String colDept= "Dept" ; • static final String deptTable= "Dept" ; • static final String colDeptID= "DeptID" ; • static final String colDeptName= "DeptName" ; • public DatabaseHelper(Context context) { • super (context, dbName, null, dbVersion); • } • }

  30. onCreate(SQLiteDatabase db) public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL( "CREATE TABLE " + deptTable + " (" + colDeptID + " INTEGER, " + colDeptName + " TEXT);" ); db.execSQL( "CREATE TABLE " + employeeTable + " (" + colID + " INTEGER, " + colName + " TEXT, " + colAge + " INTEGER, " + colDept + " INTEGER);" ); } // SQLiteOpenHelper class is a helper class in Android to manage database creation and version management // The onCreate() method creates a new database if the required database is not present. // The onUpgrade() method is called when the database needs to be upgraded. // Using Cursor enables Android to more efficiently manage rows and columns as needed

  31. Handling Records SQLiteDatabase db=this.getWritableDatabase(); //Inserting Records ContentValues cv=new ContentValues(); cv.put(colDeptID, 1); cv.put(colDeptName, "Sales"); db.insert(deptTable, colDeptID, cv); db.execSQL( “INSERT INTO “ + deptTable + “ ( “ + colDeptID + “,” + colDeptName + “) values ( ‘2', ‘Services' ); "); //Deleting Record db.delete(deptTable, colDeptID + "=" + dept_1, null); //dept_1=“1” //Updating Record cv.put(colDeptName, “newIT” ); db.update(deptTable, cv, colDeptID + "=?", dept_2); //dept_2=“2” db.close(); http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

  32. Querying SQL • SQL Select Syntax • (see http://www.sqlite.org/lang.html) • SQL-select statements are based on the following components • The first two lines are mandatory, the rest is optional.

  33. Querying SQLite • SQLiteDatabase.query() returns a Cursor object that points to results • Cursor is a iterator. Call moveToNext() to get to next element. • Cursor can be examined at runtime • getCount(), getColumnCount() • getColumnIndex(String name) • getColumnName(int index) • getInt(int index), getLong(int index), getString(int index), etc. • To upgrade the database, change the DATABASE_VERSION constant to a value higher than the previous one

  34. Querying SQLite – query() • Android Simple Queries • The signature of the Android’s simple query method is: • http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

  35. Querying SQLite – Example • Android Simple Queries Example • Query the EmployeeTable, find the average salary of female employees • supervised by 123456789. Report results by Dno. List first the highest average, • and so on, do not include depts. having less than two employees.

  36. Cursor – Example

  37. SQLite • Pre-create the database using tools like • SQLite Database Browser: http://sourceforge.net/projects/sqlitebrowser/ • A filename for files added to the assets folder must be in lowercase letters • NOTE: For the SharedPreferences object (by default) and the SQLite database, the data is accessible only by the application that creates it. In other words, it is not shareable. If you need to share data among different applications, you need to create a content provider • By default, SharedPreferences are not shareable. But changing the mode to “World Readable” or “World Writable”, you could make SharedPreferences as shareable among different applications.

  38. SQL • Creating a table: CREATE TABLE table (col1 type, col2 type, …) • Inserting into a table: INSERT INTO table (col1, col2, …) VALUES (val1, val2,…) • Updating a table: UPDATE table SET col2 = newVal2 WHERE col1 = val1 • Deleting from a table: DELETE FROM table WHERE col1 = val1 • Create a String array of result_columns for the columns of data you want to retrieve • String[] cols = new String[] {col1, col2, …}; • Create a cursor object that retrieves the result of the query • Cursor cursor = db.query(table, cols, whereClause, selectionArgs, groupBy, having, orderBy) • All are parameters for how to filter data

  39. SQL • query() returns a Cursor object • Relevant Cursor functions • getCount(): Returns the number of elements returned in Cursor • moveToFirst(), moveToNext(): Moves between the rows in the Cursor • getColumnIndexOrThrow(String col): Gets the index of the column for the parameter • Display the data • List<Object> • Create a list of your stored objects • ArrayAdapter<Object> • Bind each object to an item layout

  40. Content Provider • A content provider makes a specific set of the application's data available to other applications • => Share data to other apps • Any app with appropriate permission, can read and write the data. • Many native databases are available via the content providers, for example Contact Manager • Common interface for querying the data – consistent approach to add or delete or query or edit content

  41. About Content Provider • Content providers expose their data as a simple table on a database model • Every record includes a numeric _ID field that uniquely identifies the record within the table.

  42. About Content Provider • Content provider exposes a public URI that uniquely identifies its data set: content://<Authority>/[data_path]/[instance identifier] • the URI starts with content:// scheme. • Authority is a unique identifier for the content provider. Example “ contacts”. • data_path specifies the kind of data requested. For example, “ people ” is used to refer to all the contacts within “ contacts ”. • there can be an instance identifier that refers to a specific data instance. • content://media/internal/images - return the list of all internal images on the device. • content://media/external/images - return the list of all the images on external storage (e.g., SD card) on the device. • content://call_log/calls - return a list of all the calls registered in the call log. • content://browser/bookmarks - return a list of bookmarks stored in the browser. • content://contacts/people/45 - return the single result row, the contact with ID=45.

  43. Android Native ContentProvider • Browser — Read or modify bookmarks, browser history, or web searches. • CallLog — View or update the call history. • Contacts — Retrieve, modify, or store the personal contacts. three-tier data model of tables under a ContactsContract object: • ContactsContract.Data — Contains all kinds of personal data. • ContactsContract.RawContacts — Contains a set of Data objects associated with a single account or person. • ContactsContract.Contacts — Contains an aggregate of one or more RawContacts, presumably describing the same person. • MediaStore — Access audio, video, and images. • Setting — View and retrieve Bluetooth settings, ring tones, and other device preferences.

  44. Android Native ContentProvider • Android defines CONTENT_URI constants for all the providers that come with the platform. • ContactsContract.CommonDataKinds.Phone.CONTENT_URI (content://com.android.contacts/data/phones) • Browser.BOOKMARKS_URI • (content://browser/bookmarks) • MediaStore.Video.Media.EXTERNAL_CONTENT_URI (content://media/external/video/media) • Browser.SEARCHES_URI • CallLog.CONTENT_URI • MediaStore.Images.Media.INTERNAL_CONTENT_URI • MediaStore.Images.Media.EXTERNAL_CONTENT_URI • Settings.CONTENT_URI • Classes section under : • http://developer.android.com/reference/android/provider/package-summary.html (if a provider, CONTENT_URI field exist)

  45. Android Native ContentProvider

  46. Querying Native Content Provider • You need • URI • ContactsContract.Contacts.CONTENT_URI • Names of data fields (result comes in table) • ContactsContract.Contacts.DISPLAY_NAME • Data types of those fields • String • Remember to modify the manifest file for permissions! • To retrieve the contacts: • <uses-permission android:name="android.permission.READ_CONTACTS"> • </uses-permission>

  47. Content Provider • The equivalent of • Uri allContacts = Uri.parse(“content://contacts/people/1”); • Is using predefined constant together with the withAppendedId() method of the ContentUris class: • import android.content.ContentUris; • ... • Uri allContacts = ContentUris.withAppendedId( • ContactsContract.Contacts.CONTENT_URI, 1); • Remember to modify the manifest file for permissions!

  48. Query import android.provider.Contacts.People ; import android.content.ContentUris ; import android.net.Uri ; import android.database.Cursor ; // Use the ContentUris method to produce the base URI for the contact with _ID == 23. // “content://com.android.contacts/people/23” Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI , 23); // Alternatively, use the Uri method to produce the base URI. // It takes a string rather than an integer. // “content://com.android.contacts/people/23” Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI , "23"); // Then query for this specific record: Cursor cur = managedQuery(myPerson, null, null, null, null); // second parameter of managedQuery (third in CursorLoader class) is called as projectection. It indicates how many columns are returned by the query // third and fourth parameters (fourth and fifth in CursorLoader class) are for filtering // last parameter is for sorting For more information on URI handling functions: http://developer.android.com/reference/android/net/Uri.html

  49. Query import android.provider.Contacts.People; import android.database.Cursor; // Form an array specifying which columns to return. String [] projection = new String [] {People._ID, People._COUNT, People.NAME, People.NUMBER}; // Get the base URI for the People table in the Contacts content provider. Uri contacts = People.CONTENT_URI; // Make the query. // managedQuery is deprecated Cursor managedCursor = managedQuery(contacts, projection, // Which columns to return null, // Which rows to return (all rows) null, // Selection arguments (none) // Put the results in ascending order by name People.NAME + "ASC");

  50. Query • Instead of managedQuery() use Content Resolver • Content Resolver • getContentResolver().query( ) • getContentResolver().insert( ) • getContentResolver().update( ) • getContentResolver().delete( ) • Cursor cur = managedQuery( ) is equivalent to Cursor cur = getContentResolver().query( ); startManagingCursor(cur); • Starting HoneyComb(API level 11) CursorLoader cl = new CursorLoader(this, ); Cursor cur = cl.loadInBackground() • The CursorLoader class (only available beginning with Android API level 11 and later) performs the cursor query on a background thread and hence does not block the application UI

More Related