Android Tutorial - Core Class : SharedPreferences
Store information into Preference
package app.test; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.text.TextUtils; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class Test extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnabled(true); webview.setWebViewClient(mClient); webview.addJavascriptInterface(new MyJavaScriptInterface(), "BRIDGE"); setContentView(webview); webview.loadUrl("file:///android_asset/form.html"); } private static final String JS_SETELEMENT = "javascript:document.getElementById('%s').value='%s'"; private static final String JS_GETELEMENT = "javascript:window.BRIDGE.storeElement('%s',document.getElementById('%s').value)"; private static final String ELEMENTID = "emailAddress"; private WebViewClient mClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(String.format(JS_GETELEMENT, ELEMENTID, ELEMENTID)); return false; } @Override public void onPageFinished(WebView view, String url) { SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE); view.loadUrl(String.format(JS_SETELEMENT, ELEMENTID, prefs.getString(ELEMENTID, ""))); } }; private class MyJavaScriptInterface { public void storeElement(String id, String element) { SharedPreferences.Editor edit = getPreferences(Activity.MODE_PRIVATE).edit(); edit.putString(id, element); edit.commit(); if(!TextUtils.isEmpty(element)) { Toast.makeText(Test.this, element, Toast.LENGTH_SHORT).show(); } } } } /*<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <form name="input" action="form.html" method="get"> Enter Email: <input type="text" id="emailAddress" /> <input type="submit" value="Submit" /> </form> </html>*/
Edit Preferences
package com.commonsware.android.simple; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } //src\com\commonsware\android\simple\SimplePrefsDemo.java package com.commonsware.android.simple; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class SimplePrefsDemo extends Activity { private static final int EDIT_ID = Menu.FIRST+2; private TextView checkbox=null; private TextView ringtone=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); checkbox=(TextView)findViewById(R.id.checkbox); ringtone=(TextView)findViewById(R.id.ringtone); } @Override public void onResume() { super.onResume(); SharedPreferences prefs=PreferenceManager .getDefaultSharedPreferences(this); checkbox.setText(new Boolean(prefs .getBoolean("checkbox", false)) .toString()); ringtone.setText(prefs.getString("ringtone", "<unset>")); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit Prefs") .setIcon(R.drawable.misc) .setAlphabeticShortcut('e'); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case EDIT_ID: startActivity(new Intent(this, EditPreferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow> <TextView android:text="Checkbox:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox" /> </TableRow> <TableRow> <TextView android:text="Ringtone:" android:paddingRight="5px" /> <TextView android:id="@+id/ringtone" /> </TableRow> </TableLayout> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">SimplePrefsDemo</string> <string name="checkbox">checkbox</string> <string name="ringtone">ringtone</string> </resources> //res\xml\preferences.xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="checkbox" android:title="Checkbox Preference" android:summary="Check it on, check it off" /> <RingtonePreference android:key="ringtone" android:title="Ringtone Preference" android:showDefault="true" android:showSilent="true" android:summary="Pick a tone, any tone" /> </PreferenceScreen>
Structured Preferences
package com.commonsware.android.prefs; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } //src\com\commonsware\android\prefs\StructuredPrefsDemo.java package com.commonsware.android.prefs; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class StructuredPrefsDemo extends Activity { private static final int EDIT_ID = Menu.FIRST+2; private TextView checkbox=null; private TextView ringtone=null; private TextView checkbox2=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); checkbox=(TextView)findViewById(R.id.checkbox); ringtone=(TextView)findViewById(R.id.ringtone); checkbox2=(TextView)findViewById(R.id.checkbox2); } @Override public void onResume() { super.onResume(); SharedPreferences prefs=PreferenceManager .getDefaultSharedPreferences(this); checkbox.setText(new Boolean(prefs .getBoolean("checkbox", false)) .toString()); ringtone.setText(prefs.getString("ringtone", "<unset>")); checkbox2.setText(new Boolean(prefs .getBoolean("checkbox2", false)) .toString()); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit Prefs") .setIcon(R.drawable.misc) .setAlphabeticShortcut('e'); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case EDIT_ID: startActivity(new Intent(this, EditPreferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow> <TextView android:text="Checkbox:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox" /> </TableRow> <TableRow> <TextView android:text="Ringtone:" android:paddingRight="5px" /> <TextView android:id="@+id/ringtone" /> </TableRow> <TableRow> <TextView android:text="Checkbox #2:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox2" /> </TableRow> </TableLayout> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">StructuredPrefsDemo</string> <string name="checkbox">checkbox</string> <string name="ringtone">ringtone</string> <string name="checkbox2">checkbox2</string> </resources> //res\xml\preferences.xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Simple Preferences"> <CheckBoxPreference android:key="checkbox" android:title="Checkbox Preference" android:summary="Check it on, check it off" /> <RingtonePreference android:key="ringtone" android:title="Ringtone Preference" android:showDefault="true" android:showSilent="true" android:summary="Pick a tone, any tone" /> </PreferenceCategory> <PreferenceCategory android:title="Detail Screens"> <PreferenceScreen android:key="detail" android:title="Detail Screen" android:summary="Additional preferences held in another page"> <CheckBoxPreference android:key="checkbox2" android:title="Another Checkbox" android:summary="On. Off. It really doesn't matter." /> </PreferenceScreen> </PreferenceCategory> </PreferenceScreen>
Save value to preference
package app.test; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Toast; public class Test extends Activity { private SharedPreferences prefs; private EditText editText; private SeekBar seekBar; private Button btn; private String FONT_SIZE_KEY = "fontsize"; private String TEXT_VALUE_KEY = "textvalue"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText) findViewById(R.id.EditText01); seekBar = (SeekBar) findViewById(R.id.SeekBar01); btn = (Button) findViewById(R.id.btnSave); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //---get the SharedPreferences object--- //prefs = getSharedPreferences(prefName, MODE_PRIVATE); prefs = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); //---save the values in the EditText view to preferences--- editor.putFloat(FONT_SIZE_KEY, editText.getTextSize()); editor.putString(TEXT_VALUE_KEY, editText.getText().toString()); editor.commit(); Toast.makeText(getBaseContext(), "Font size saved successfully!", Toast.LENGTH_SHORT).show(); } }); //---load the SharedPreferences object--- //SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE); prefs = getPreferences(MODE_PRIVATE); float fontSize = prefs.getFloat(FONT_SIZE_KEY, 12); seekBar.setProgress((int) fontSize); editText.setText(prefs.getString(TEXT_VALUE_KEY, "")); editText.setTextSize(seekBar.getProgress()); seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { editText.setTextSize(progress); } }); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <SeekBar android:id="@+id/SeekBar01" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/TextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btnSave" android:text="Save" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Example that shows finding a preference from the hierarchy and a custom preference type.
package com.example.android.apis.preference; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.preference.CheckBoxPreference; import android.widget.Toast; /** * Example that shows finding a preference from the hierarchy and a custom preference type. */ public class AdvancedPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener { public static final String KEY_MY_PREFERENCE = "my_preference"; public static final String KEY_ADVANCED_CHECKBOX_PREFERENCE = "advanced_checkbox_preference"; private CheckBoxPreference mCheckBoxPreference; private Handler mHandler = new Handler(); /** * This is a simple example of controlling a preference from code. */ private Runnable mForceCheckBoxRunnable = new Runnable() { public void run() { if (mCheckBoxPreference != null) { mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked()); } // Force toggle again in a second mHandler.postDelayed(this, 1000); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the XML preferences file addPreferencesFromResource(R.xml.advanced_preferences); // Get a reference to the checkbox preference mCheckBoxPreference = (CheckBoxPreference)getPreferenceScreen().findPreference( KEY_ADVANCED_CHECKBOX_PREFERENCE); } @Override protected void onResume() { super.onResume(); // Start the force toggle mForceCheckBoxRunnable.run(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); // Unregister the listener whenever a key changes getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); mHandler.removeCallbacks(mForceCheckBoxRunnable); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Let's do something when my counter preference value changes if (key.equals(KEY_MY_PREFERENCE)) { Toast.makeText(this, "Thanks! You increased my count to " + sharedPreferences.getInt(key, 0), Toast.LENGTH_SHORT).show(); } } } //xml/advanced_preferences.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <com.example.android.apis.preference.MyPreference android:key="my_preference" android:title="@string/title_my_preference" android:summary="@string/summary_my_preference" android:defaultValue="100" /> <CheckBoxPreference android:key="advanced_checkbox_preference" android:title="@string/title_advanced_toggle_preference" android:summaryOn="@string/summary_on_advanced_toggle_preference" android:summaryOff="@string/summary_off_advanced_toggle_preference" /> </PreferenceScreen>
Increment Access Count
//package org.anddev.andengine.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; class SimplePreferences { private static SharedPreferences INSTANCE; private static Editor EDITORINSTANCE; public static SharedPreferences getInstance(final Context pContext) { if(SimplePreferences.INSTANCE == null) { SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); } return SimplePreferences.INSTANCE; } public static Editor getEditorInstance(final Context pContext) { if(SimplePreferences.EDITORINSTANCE == null) { SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); } return SimplePreferences.EDITORINSTANCE; } public static int incrementAccessCount(final Context pContext, final String pKey) { return SimplePreferences.incrementAccessCount(pContext, pKey, 1); } public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) { final SharedPreferences prefs = SimplePreferences.getInstance(pContext); final int accessCount = prefs.getInt(pKey, 0); final int newAccessCount = accessCount + pIncrement; prefs.edit().putInt(pKey, newAccessCount).commit(); return newAccessCount; } public static int getAccessCount(final Context pCtx, final String pKey) { return SimplePreferences.getInstance(pCtx).getInt(pKey, 0); } }
finish When Expired
//package org.anddev.andengine.util; import java.util.GregorianCalendar; import android.R; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; public class BetaUtils { private static final String PREFERENCES_BETAUTILS_ID = "preferences.betautils.lastuse"; // // Getter & Setter // // // Methods from SuperClass/Interfaces // // // Methods // public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID) { return BetaUtils.finishWhenExpired(pActivity, pExpirationDate, pTitleResourceID, pMessageResourceID, null, null); } public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID, final Intent pOkIntent, final Intent pCancelIntent) { final SharedPreferences spref = SimplePreferences.getInstance(pActivity); final long now = System.currentTimeMillis(); final long lastuse = Math.max(now, spref.getLong(PREFERENCES_BETAUTILS_ID, -1)); spref.edit().putLong(PREFERENCES_BETAUTILS_ID, lastuse).commit(); final GregorianCalendar lastuseDate = new GregorianCalendar(); lastuseDate.setTimeInMillis(lastuse); if(lastuseDate.after(pExpirationDate)){ final Builder alertDialogBuilder = new AlertDialog.Builder(pActivity) .setTitle(pTitleResourceID) .setIcon(R.drawable.ic_dialog_alert) .setMessage(pMessageResourceID); alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){ @Override public void onClick(final DialogInterface pDialog, final int pWhich) { if(pOkIntent != null) { pActivity.startActivity(pOkIntent); } pActivity.finish(); } }); alertDialogBuilder.setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { if(pCancelIntent != null) { pActivity.startActivity(pCancelIntent); } pActivity.finish(); } }) .create().show(); return true; }else{ return false; } } // // Inner and Anonymous Classes // } class SimplePreferences { // // Constants // // // Fields // private static SharedPreferences INSTANCE; private static Editor EDITORINSTANCE; // // Constructors // public static SharedPreferences getInstance(final Context pContext) { if(SimplePreferences.INSTANCE == null) { SimplePreferences.INSTANCE = PreferenceManager.getDefaultSharedPreferences(pContext); } return SimplePreferences.INSTANCE; } public static Editor getEditorInstance(final Context pContext) { if(SimplePreferences.EDITORINSTANCE == null) { SimplePreferences.EDITORINSTANCE = SimplePreferences.getInstance(pContext).edit(); } return SimplePreferences.EDITORINSTANCE; } // // Getter & Setter // // // Methods for/from SuperClass/Interfaces // // // Methods // public static int incrementAccessCount(final Context pContext, final String pKey) { return SimplePreferences.incrementAccessCount(pContext, pKey, 1); } public static int incrementAccessCount(final Context pContext, final String pKey, final int pIncrement) { final SharedPreferences prefs = SimplePreferences.getInstance(pContext); final int accessCount = prefs.getInt(pKey, 0); final int newAccessCount = accessCount + pIncrement; prefs.edit().putInt(pKey, newAccessCount).commit(); return newAccessCount; } public static int getAccessCount(final Context pCtx, final String pKey) { return SimplePreferences.getInstance(pCtx).getInt(pKey, 0); } // // Inner and Anonymous Classes // }
Store your information into SharedPreferences
package app.test; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.widget.Button; import android.widget.TextView; public class HomeActivity extends Activity implements View.OnClickListener { Button settingsButton; TextView displayText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); PreferenceManager.setDefaultValues(this, R.xml.settings, false); displayText = (TextView)findViewById(R.id.display); settingsButton = (Button)findViewById(R.id.settings); settingsButton.setOnClickListener(this); } @Override public void onResume() { super.onResume(); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); StringBuilder builder = new StringBuilder(); builder.append("User Name: "+settings.getString("namePref", "")+"\n"); if(!settings.getBoolean("morePref", false)) { builder.append("More Settings is DISABLED"); } else { builder.append("More Settings is ENABLED\n"); builder.append("Favorite Color is "+settings.getString("colorPref", "")+"\n"); builder.append(settings.getBoolean("myGPS", false) ? "GPS is ENABLED\n" : "GPS is DISABLED\n"); } displayText.setText(builder.toString()); } @Override public void onClick(View v) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } } //SettingsActivity.java package app.test; import android.os.Bundle; import android.preference.PreferenceActivity; public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); } } //arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="color_names"> <item>Black</item> <item>Red</item> <item>Green</item> </string-array> <string-array name="color_values"> <item>BLK</item> <item>RED</item> <item>GRN</item> </string-array> </resources> //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Current Settings:" /> <TextView android:id="@+id/display" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dip" /> <Button android:id="@+id/settings" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Settings" /> </LinearLayout> //settings.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <EditTextPreference android:key="namePref" android:title="Name" android:summary="Tell Us Your Name" android:defaultValue="Apress" /> <CheckBoxPreference android:key="morePref" android:title="Enable More Settings" android:defaultValue="false" /> <PreferenceScreen android:key="moreScreen" android:title="More Settings" android:dependency="morePref"> <ListPreference android:key="colorPref" android:title="Favorite Color" android:summary="Choose your favorite color" android:entries="@array/color_names" android:entryValues="@array/color_values" android:defaultValue="GRN" /> <PreferenceCategory android:title="Location Settings"> <CheckBoxPreference android:key="myGPS" android:title="Use GPS Location" android:summary="Use GPS to Find You" android:defaultValue="true" /> </PreferenceCategory> </PreferenceScreen> </PreferenceScreen>