Android Programming: Lecture 08

2,363
-1

Published on

1) Sharing SharedPreferences
2) SharedPreferences and Bundles to Persist UI States
3) Data Persistence with Databases
4) Lite Intro to SQLite
5) Working with SQLite Databases
6) Class home page is at http://vkedco.blogspot.com/2011/08/android-programming-home.html

Published in: Software, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,363
On Slideshare
0
From Embeds
0
Number of Embeds
30
Actions
Shares
0
Downloads
1
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Android Programming: Lecture 08

  1. 1. Android Programming Lecture 08 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Resources Source code and presentation materials for this lecture are available at http://vkedco.blogspot.com/2011/10/android-programming-lecture-08.htmlwww.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. Outline ● Sharing Shared Preferences ● Using Shared Preferences and Bundles to Persist UI States ● Data Persistence with Databases ● Lite Intro to SQLite ● Working with SQLite Databaseswww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. Sharing Shared Preferenceswww.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. Sharing SharedPreferences ● Shared preferences key/value pairs are stored against the application context ● Any application component such as activities, services, and broadcast receivers can access those values by getting the applications contextwww.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. Finding and Using Shared Preferences Context context = getApplicationContext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // Use type safe getter methods on prefs to get the values: // prefs.getInt(...); prefs.getBoolean(...); etc.www.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. SharedPrefs2 Projectwww.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. Using Shared Preferences and Bundles to Persist Activitys UI Stateswww.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Saving Activity State ● If an activity saves some information that does not need to be shared with other components, Activity.getPreferences() can be used ● Access to the SharedPreferences object returned by Activity.getPreferences() is restricted only to the calling activity ● Each activity supports only one unnamed SharedPreferences objectwww.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. Saving Activity State protected void saveActivityPreferences() { SharedPreferences activityPrefs = getPreferences(Activity.MODE_PRIVATE); SharedPreferences.Editor edtr = activityPrefs.edit(); TextView tv = (TextView)findViewById(R.id.myTV); edtr.putString(“my_key_val”, tv.getText().toString()); edtr.commit(); }www.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Saving and Restoring Activitys State ● It is possible to save Activitys state through Bundles by overriding Activity.onSaveInstanceState() ● The type safe put methods must be used on the Bundle object before passing the modified Bundle object to the super class ● Activity.onSaveInstanceState() handler is automatically triggered when the Activity completes its active lifecycle but not when it is being explicitly finished with a call to finish() or by the users pressing the back buttonwww.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. Saving Activity Instance State private static final String MY_KEY = “my_key”; @Override public void onSaveInstanceState(Bundle saveInstanceState) { TextView tv = (TextView)findViewById(R.id.my_tv); saveInstanceState.putString(my_key, tv.getText().toString()); super.onSaveInstanceState(saveInstanceState); }www.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. Restoring Activity Instance State private static final String MY_KEY = “my_key”; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = (TextView)findViewById(R.id.my_tv); String text = “”; if ( savedInstanceState != null && savedInstanceState.containsKey(MY_KEY)) text = savedInstanceState.getString(MY_KEY); tv.setText(text); }www.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. Saving ToDoList Activity State ● ToDoList Activity in Chapter 05 does not save its state ● If the application is exited: – Any text entered in the task entrys edit text box is cleared – The application does not know if a new task was being added – The application does not know which task was selectedwww.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. Saving Activity State: Logical Steps ● Define string constants for preference keys ● Override the activitys onPause() method which is triggered when the user is leaving your activity and use SharedPreferences to commit the current activitys UI state ● Implement a private restoreUIState() method that gets the saved SharedPreferences object and restores the UI state ● Call restoreUIState() from onCreate() ● Override onSaveInstanceState() and onRestoreInstanceState() to save/restore selected itemswww.youtube.com/vkedco www.vkedco.blogspot.com
  16. 16. Define String Constants for Preference Keys private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY"; private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY"; private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY";www.youtube.com/vkedco
  17. 17. Override Activitys onPause() Method protected void onPause() { super.onPause(); SharedPreferences uiState = this.getPreferences(Activity.MODE_PRIVATE); SharedPreferences.Editor edtr = uiState.edit(); edtr.putString(TEXT_ENTRY_KEY, myEditText.getText().toString()); edtr.putBoolean(ADDING_ITEM_KEY, addingNew); edtr.commit(); }www.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. Implement restoreUIState() Method private void restoreUIState() { SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE); String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); if ( adding ) { addNewItem(); myEditText.setText(text); } }www.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Implement restoreUIState() Method private void restoreUIState() { SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE); String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); if ( adding ) { addNewItem(); myEditText.setText(text); } }www.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Call restoreUIState() from onCreate() resID = R.layout.todolist_item_ch5; todoItemsList = new ArrayList<ToDoItem>(); aryadptr3 = new ToDoItemAdapter(this, resID, todoItemsList); myListView.setAdapter(aryadptr3); restoreUIState();www.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. Override onSaveInstanceState() and onRestoreInstanceState() public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition()); super.onSaveInstanceState(savedInstanceState); }www.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. Override onSaveInstanceState() and onRestoreInstanceState() public void onRestoreInstanceState(Bundle savedInstanceState) { int pos = -1; if ( savedInstanceState != null ) { if ( savedInstanceState.containsKey(SELECTED_INDEX_KEY) ) { pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1); } } myListView.setSelection(pos); }www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. ToDoListCh2 Demowww.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. Saving and Loading Files ● Do not forget that it is possible to save and load files in and from the currrent applications folder with openFileOutput() and openFileInput() ● It is also possible to include external files into your distribution package by placing them into /res/raw/ ● Reasonable option for large data sources that your application will need at run timewww.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. File Management ● File management is useful for cleanup ● Android supports basic file management in java.io.File ● Two useful methods of the applications Context: – deleteFile() can be used to remove files created by the current application – fileList() option for large data sources that your application will need at run time ● getApplicationContext().deleteFile(String name)www.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. Data Persistence with Databaseswww.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. SharedPreferences: Pros and Cons ● Pros – Lightweight – Easy to code and debug ● Cons – Slow with large data volumes – Not helpful key/value pairs are not sufficient – Entire file needs to be read and parsed to access data – Takes up more space because XML is used for storagewww.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. SQLite: Pros and Cons ● Pros – Scalable – Incremental changes – Flexible queries ● Cons – Heavyweight: code and memory – Harder to code and maintainwww.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. SQLite Databases on Android ● Android offers SQLite relational database library ● Every application can create its own database over which it has complete control ● SQLite databases should be considered to manage complex, structured data ● Databases are stored in /data/data/<package_name>/databases/www.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. Database Design ● Standard database design practices apply on Android ● A key design principle is to manage space well: reduce redundancy via database normalization ● The objective of database normalization is to decompose relations with anomalies to produce smaller, well structured relations ● Source: en.wikipedia.org/Database_normalizationwww.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Lite Intro to SQLitewww.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. What is SQLite? ● SQLite is a relational database management system (RDBMS) ● SQLite is a compact C library that is part of the Android software stack ● Since it is a library, it can be integrated into each application without external dependencies: this simplifies transactions and synchronizations, minimizes latencywww.youtube.com/vkedco
  33. 33. What is SQLite? ● SQLite has a reputation of being reliable ● SQLite is the database management system for many MP3 players, the iPhone, and the iPod ● Key difference: loose column typing – column values are not required to conform to a single type; each value is typed individually for each row ● Source: http://www.sqlite.orgwww.youtube.com/vkedco
  34. 34. ContentValues and Cursors ● Rows are inserted into tables with objects of the ContentValues class ● Each ContentValues object is a map of column names to column values ● Queries on Android SQLite databases are returned as Cursor objects ● Cursor objects are pointers to the result setwww.youtube.com/vkedco www.vkedco.blogspot.com
  35. 35. Some Cursor Class Methods ● moveToFirst() - moves the cursor to the first row of the result set ● moveToNext() - moves the cursor to the next row of the result set ● moveToPrevious() - moves the cursor to the previous row of the result set ● getCount() - returns the number of rows in the result setwww.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. Cursor Management ● startManagingCursor() - integrates the cursors lifetime into the calling activitys lifetime ● stopManagingCursor() - stops managing the cursor when it is no longer neededwww.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. Working with SQLite Databaseswww.youtube.com/vkedco www.vkedco.blogspot.com
  38. 38. Basic Guidelines ● It is always a good idea to create a database adapter class to manage database transactions ● The database adapter class handles queries and includes methods for creating, opening, and closing the database ● In this adapter class, one can create a database helper class that provides strongly typed methods for adding remove and updating items ● The adapter class also publishes static database constantswww.youtube.com/vkedco
  39. 39. DBAdapter Class public class MyDBAdapter { public static final String DB_NAME = “myDB.db”; public static final String DB_TABLE = “mainTBL”; public static final int DB_VERSION = 1; public static final String KEY_ID = “_id”; public static final String KEY_NAME = “key_name”; public static final String int NAME_COLUMN = 1; }www.youtube.com/vkedco www.vkedco.blogspot.com
  40. 40. DBAdapter Class private static final String DB_CREATE = “create table “ + DB_TABLE + “ (“ + KEY_ID + “ integer primary key autoincrement, “ + KEY_NAME + “ text not null);”; private SQLiteDabase db; private final Context context; private myDBHelper dbHelper;www.youtube.com/vkedco www.vkedco.blogspot.com
  41. 41. DBHelper Class in DBAdapter Class private static class myDBHelper extends SQLiteOpenHelper { public myDBHelper(Context context, String name, CursorFactory cfact, int version) { super(context, name, cfact, version); } public void onCreate(SQLiteDatabase db) { db.execSQL(DB_CREATE); } }www.youtube.com/vkedco www.vkedco.blogspot.com
  42. 42. DBHelper Class in DBAdapter Class // This is the simplest method of dropping the table private static class myDBHelper extends SQLiteOpenHelper { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(“DROP TABLE IF EXISTS “ + DB_TABLE); onCreate(db); } }www.youtube.com/vkedco www.vkedco.blogspot.com
  43. 43. SQLiteOpenHelper Class ● SQLiteOpenHelper is an abstract class the implements the best practices patterns for creating, opening, and upgrading databases ● Two most important methods are: – getReadableDatabase() – getWriteableDatabase()www.youtube.com/vkedco www.vkedco.blogspot.com
  44. 44. SQLiteOpenHelper DB Access DbHelper dbHelper = new myDBHelper(context, DB_NAME, null, DB_VERSION); SQLiteDatabase db; try { db = dbHelper.getWriteableDatabase(); } catch ( SQLiteException ex ) { db = dbHelper.getReadableDatabase(); }www.youtube.com/vkedco www.vkedco.blogspot.com
  45. 45. Extracting Values from Cursors Cursor rsltCursor = myDB.query(“RESULTS”, null, null, null, null, null, null); int MY_COL = 1; float totalSum = 0f; if ( rsltCursor.moveToFirst() ) { do { float colVal = rsltCursor.getFloat(MY_COL); totalSum += colVal; } while ( rsltCursor.moveToNext() ); }www.youtube.com/vkedco www.vkedco.blogspot.com
  46. 46. Inserting Rows ContentValues newRow = new ContentValues(); newRow.put(COL_NAME, colValue); … myDB.insert(DB_TABLE, null, newRow);www.youtube.com/vkedco www.vkedco.blogspot.com
  47. 47. Updating and Deleting Rows ContentValues updatedRow = new ContentValues(); newRow.put(COL_NAME, colValue); String where = KEY_ID + “=” + rowID; myDB.update(DB_TABLE, newRow, where, null); myDB.delete(DATABASE_TABLE, KEY_ID + ”=” + rowID, null);www.youtube.com/vkedco www.vkedco.blogspot.com
  48. 48. References & Reading Suggestions ● http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html ● http://developer.android.com/guide/topics/data/data-storage.html ● Chapters 6, 7 in “Professional Android 2 Application Development” by Rito Meier ● http://www.sqlite.orgwww.youtube.com/vkedco www.vkedco.blogspot.com
  49. 49. Feedback Comments, typos, bugs to vladimir dot kulyukin at gmail dot comwww.youtube.com/vkedco www.vkedco.blogspot.com

×