App Development for Smart Devices CS 495/595 - Fall 2011 Lec #4: Files, Saving State, and Preferences Tamer Nadeem Dept. of Computer Science Some slides adapted from Stephen Intille
Objective Data Storage Shared Preferences Data Files Two design papers Case Studies (1-6) Presenter: Tony Chiou Case Studies (7-13) Presenter: Ashok Kumar Page 2 Fall 2011 CS 495/595 - App Development for Smart Devices
Saving data Your options (most complex apps use all) Shared Preferences Bundles Local files Local database (SQLite) Remote database Saving data obviously essential Page 3 Fall 2011 CS 495/595 - App Development for Smart Devices
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 Page 4 Fall 2011 CS 495/595 - App Development for Smart Devices
Saving other info Application preferences UI selections Data entry Page 5 Fall 2011 CS 495/595 - App Development for Smart Devices
Shared Preferences Page 6 Spring 2011 CS 752/852 - Wireless and Mobile Networking
Shared Preferences Simple, lightweight key/value pair (or name/value pair NVP) mechanism Support primitive types: Boolean, string, float, long and integer 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(); } } Page 7 Fall 2011 CS 495/595 - App Development for Smart Devices
Using Shared Preferences Shared across an application s components, but are not available to other applications Caveat: they can be made available to multiple processes within same application, but be careful Stored as XML in the protected application directory on main memory (usually /data/data/<package name>/shared_prefs/<sp Name>.xml) Page 8 Fall 2011 CS 495/595 - App Development for Smart Devices
DDMS-File Explorer (Window > Open Perspective > Other... > DDMS) http://developer.android.com/guide/developing/debugging/ddms.html Page 9 Fall 2011 CS 495/595 - App Development for Smart Devices
Creating and Sharing Prefs public static String MY_PREFS = "MY_PREFS"; int mode = Activity.MODE_PRIVATE; SharedPreferences mysharedpreferences = 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(); Page 10 Fall 2011 CS 495/595 - App Development for Smart Devices
Retrieving public static String MY_PREFS = "MY_PREFS"; public void loadpreferences() { // Get the stored preferences int mode = Activity.MODE_PRIVATE; SharedPreferences mysharedpreferences = getsharedpreferences(my_prefs, mode); } // Retrieve the saved values. boolean istrue = mysharedpreferences.getboolean("istrue", false); float lastfloat = mysharedpreferences.getfloat("lastfloat", 0f); int wholenumber = mysharedpreferences.getint("wholenumber", 1); long anumber = mysharedpreferences.getlong("anumber", 0); String stringpreference = mysharedpreferences.getstring("textentryvalue", ""); Page 11 Fall 2011 CS 495/595 - App Development for Smart Devices
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 Page 12 Fall 2011 CS 495/595 - App Development for Smart Devices
Preference Activity XML <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android: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> Page 13 Fall 2011 CS 495/595 - App Development for Smart Devices
Preference Activity Options CheckBoxPreference EditTextPreference ListPreference RingtonePreference Page 14 Fall 2011 CS 495/595 - App Development for Smart Devices
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); Page 15 Fall 2011 CS 495/595 - App Development for Smart Devices
Using prefs from Pref. Activity Recorded shared prefs are stored in Application Context. Therefore, available to any component: Activities Services BroadcastReceiver Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // then Retrieve values using get<type> method Page 16 Fall 2011 CS 495/595 - App Development for Smart Devices
SP 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 Page 17 Fall 2011 CS 495/595 - App Development for Smart Devices
SP change listeners public class MyActivity extends Activity implements OnSharedPreferenceChangeListener { @Override public void oncreate(bundle SavedInstanceState) { // Register this OnSharedPreferenceChangeListener Context context = getapplicationcontext(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.registeronsharedpreferencechangelistener(this); } } public void onsharedpreferencechanged(sharedpreferences prefs, String key) { // TODO Check the shared preference and key parameters // and change UI or behavior as appropriate. } Page 18 Fall 2011 CS 495/595 - App Development for Smart Devices
Activity Local Preferences Only be used within the activity and can not be used by other components of the application. //Storing Local Preferences SharedPreferences preferences = getpreference(mode_private); SharedPreferences.Editor editor = preferences.edit(); editor.putint("storedint", storedpreference); // value to store editor.commit(); //Retrieving Local Preferences SharedPreferences preferences = getpreferences(mode_private); int storedpreference = preferences.getint("storedint", 0); // use the values Page 19 Fall 2011 CS 495/595 - App Development for Smart Devices
Bundles Page 20 Spring 2011 CS 752/852 - Wireless and Mobile Networking
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 Page 21 Fall 2011 CS 495/595 - App Development for Smart Devices
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); Page 22 Fall 2011 CS 495/595 - App Development for Smart Devices
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. boolean myboolean = savedinstancestate.getboolean("myboolean"); double mydouble = savedinstancestate.getdouble("mydouble"); int myint = savedinstancestate.getint("myint"); String mystring = savedinstancestate.getstring("mystring"); Page 23 Fall 2011 CS 495/595 - App Development for Smart Devices
Data Files Page 24 Spring 2011 CS 752/852 - Wireless and Mobile Networking
Saving/loading files Biggest decision: location Local vs Remote Internal vs External Code is standard Java String FILE_NAME = "tempfile.tmp"; // Create a new output file stream that s private to this application. FileOutputStream fos = openfileoutput(file_name, Context.MODE_PRIVATE); // Create a new file input stream. FileInputStream fis = openfileinput(file_name); Page 25 Fall 2011 CS 495/595 - App Development for Smart Devices
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 Page 26 Fall 2011 CS 495/595 - App Development for Smart Devices
Static files as resources Only good option for small files that NEVER change Otherwise, grab on the fly from net Put in res/raw folder Resources myresources = getresources(); InputStream myfile = myresources.openrawresource(r.raw.myfilename); Page 27 Fall 2011 CS 495/595 - App Development for Smart Devices
Handling SD Card Writing Permission (AndroidManifest.xml) <uses-permission android:name="android.permission.write_external_storage"> </uses-permission> Page 28 Fall 2011 CS 495/595 - App Development for Smart Devices
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(); Page 29 Fall 2011 CS 495/595 - App Development for Smart Devices
Other data storage options Later in the course: Local database (SQLite) If you need to perform queries on data Content Providers to share data External database Grab info on demand (or overnight) If you can rely on sporadic Internet connectivity Page 30 Fall 2011 CS 495/595 - App Development for Smart Devices
Questions? Page 31 Spring 2011 CS 752/852 - Wireless and Mobile Networking
TO DO Check your paper assignment on the class webpage 8-10 slides 15-20 minutes presentations Implement Sudoku in Ch. 4 (highly recommended) Project teams (team s name, team s member) due date: Friday Sep 16 th, 11:59pm Page 32 Fall 2011 CS 495/595 - App Development for Smart Devices