Your data storage options are the following:
- Shared Preferences
- Store private primitive data in key-value pairs.
- Internal Storage
- External Storage
- SQLite Databases
- Network Connection
In this tutorial we are going to explore the Shared Preferences in many different ways
- Shared Prefernces using the Preference activity
- Manipulate the Preference summary to display the value
- Ability to put buttons on a preference screen for other actions
- Custom shared preferences not using Preference activity
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen.
To get a SharedPreferences object for your application, use one of two methods:
- getSharedPreferences()
- Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
- getPreferences()
- Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
- Call edit() to get a SharedPreferences.Editor.
- Add values with methods such as putBoolean() and putString().
- Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
Andorid application manifest file - AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.as400samplecode" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Preferences" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar"> </activity> <activity android:name=".Preferences2" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar"> </activity> <activity android:name=".Preferences3" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar"> </activity> <activity android:name=".Preferences4" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light.Dialog.NoActionBar"> </activity> </application> </manifest>
Application strings resource - strings.xml
<resources> <string name="app_name">Android Shared Preferences</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">Android Preferences Tutorial and Sample Code</string> <string name="prefs_text1">Standard Preferences</string> <string name="prefs_text2">Preferences with value displayed as summary</string> <string name="prefs_text3">Custom Preferences without extending PreferenceActivity</string> </resources>
Application array resource - arrays.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="listArray"> <item>Dog</item> <item>Cat</item> <item>Other</item> </string-array> <string-array name="listValues"> <item>1</item> <item>2</item> <item>3</item> </string-array> </resources>
Application main layout - activity_main.xml
<?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:text="@string/title_activity_main" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:id="@+id/preferences1" style="?android:attr/buttonStyleSmall" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:text="@string/prefs_text1" /> <Button android:id="@+id/preferences2" style="?android:attr/buttonStyleSmall" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/preferences1" android:text="@string/prefs_text2" /> <Button android:id="@+id/preferences3" style="?android:attr/buttonStyleSmall" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/preferences2" android:text="@string/prefs_text3" /> </RelativeLayout>
Application main Activity - MainActivity.java
package com.as400samplecode; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button preferencesButton1 = (Button) findViewById(R.id.preferences1); preferencesButton1.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent settingsActivity = new Intent(getBaseContext(), Preferences.class); startActivity(settingsActivity); } }); Button preferencesButton2 = (Button) findViewById(R.id.preferences2); preferencesButton2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent settingsActivity = new Intent(getBaseContext(), Preferences3.class); startActivity(settingsActivity); } }); Button preferencesButton3 = (Button) findViewById(R.id.preferences3); preferencesButton3.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent settingsActivity = new Intent(getBaseContext(), Preferences4.class); startActivity(settingsActivity); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
Standard Preferences XML layout - preferences.xml
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="My list of Preferences"> <CheckBoxPreference android:title="Checkbox Preference" android:defaultValue="false" android:summary="This preference can be true or false" android:key="checkboxPref" /> <ListPreference android:title="Your favorite Pet" android:summary="This preference allows to select an item in a array" android:key="listPref" android:defaultValue="digiGreen" android:entries="@array/listArray" android:entryValues="@array/listValues" /> <EditTextPreference android:name="EditText Preference" android:summary="This allows you to enter a string" android:defaultValue="Nothing" android:title="Edit This Text" android:key="editTextPref" /> <RingtonePreference android:name="Ringtone Preference" android:summary="Select a ringtone" android:title="Ringtones" android:key="ringtonePref" /> <PreferenceScreen android:key="SecondPrefScreen" android:title="Secondary Level" android:summary="This is a sub PreferenceScreen"> <intent android:action="android.intent.action.VIEW" android:targetPackage="com.as400samplecode" android:targetClass="com.as400samplecode.Preferences2" /> </PreferenceScreen> <Preference android:title="Custom Preference" android:summary="This works almost like a button" android:key="customPref" /> </PreferenceCategory> </PreferenceScreen>
Standard Preferences Activity - Preferences.java
package com.as400samplecode; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.widget.Toast; public class Preferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit(); PreferenceManager.setDefaultValues(Preferences.this, R.xml.preferences, false); } public class PrefsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Get the custom preference Preference customPref = (Preference) findPreference("customPref"); customPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Toast.makeText(getBaseContext(), "The custom preference has been clicked", Toast.LENGTH_LONG).show(); SharedPreferences customSharedPreference = getSharedPreferences( "myCustomSharedPrefs", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = customSharedPreference.edit(); editor.putString("myCustomPref", "The preference has been clicked"); editor.commit(); return true; } }); } } }
Standard sub Preferences XML layout - preferences2.xml
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="My secondary list of Preferences"> <CheckBoxPreference android:title="Checkbox Preference" android:defaultValue="false" android:summary="This preference can be true or false" android:key="checkboxPref2" /> <EditTextPreference android:name="EditText Preference" android:summary="This allows you to enter a string" android:defaultValue="Nothing" android:title="Edit This Text" android:key="editTextPref2" /> </PreferenceCategory> </PreferenceScreen>
Standard sub Preferences Activity - Preferences2.java
package com.as400samplecode; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; public class Preferences2 extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit(); PreferenceManager.setDefaultValues(Preferences2.this, R.xml.preferences, false); } public static class PrefsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences2); } } }
Preferences with summary Text XML layout - preferences3.xml
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Preferences with value displayed as summary"> <EditTextPreference android:summary="Enter URL for Web Web Connetivity" android:defaultValue="" android:title="URL for connectivity" android:key="editURLPref" /> <EditTextPreference android:summary="Enter Secret Word for secure Transactions" android:defaultValue="" android:title="Secret Word" android:key="editKey" android:password="true" /> </PreferenceCategory> </PreferenceScreen>
Preference window with close button XML layout - pref_window.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <FrameLayout android:id="@+id/displayPrefs" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </FrameLayout> <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_gravity="right" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" " android:id="@+id/textView1" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:id="@+id/close" android:layout_height="wrap_content" android:text="Close" /> </LinearLayout> </LinearLayout>
Preferences with buttons and summary Text Activity - Preferences3.java
package com.as400samplecode; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Preferences3 extends PreferenceActivity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.prefs_window); getFragmentManager().beginTransaction().replace(R.id.displayPrefs, new PrefsFragment()).commit(); PreferenceManager.setDefaultValues(Preferences3.this, R.xml.preferences3, false); Button mClose = (Button)findViewById(R.id.close); mClose.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); } public static class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences3); for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){ initSummary(getPreferenceScreen().getPreference(i)); } } @Override public void onResume(){ super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); // Unregister the listener whenever a key changes getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { updatePrefSummary(findPreference(key)); } private void initSummary(Preference p){ if (p instanceof PreferenceCategory){ PreferenceCategory pCat = (PreferenceCategory)p; for(int i=0;i<pCat.getPreferenceCount();i++){ initSummary(pCat.getPreference(i)); } }else{ updatePrefSummary(p); } } private void updatePrefSummary(Preference p){ if (p instanceof ListPreference) { ListPreference listPref = (ListPreference) p; p.setSummary(listPref.getEntry()); } if (p instanceof EditTextPreference) { EditTextPreference editTextPref = (EditTextPreference) p; if(p.getKey().equalsIgnoreCase("editKey")){ p.setSummary("I am not going to display a password!"); } else { p.setSummary(editTextPref.getText()); } } } } }
Custom Preferences without PreferenceActivity XML layout - custom_pref.xml
<?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="10dp" android:text="Custom Preferences without extending PreferenceActivity" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView1" android:layout_marginTop="20dp" android:text="EditText Preference" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView2" android:ems="10"> <requestFocus /> </EditText> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/editText1" android:text="Checkbox Preference" android:textAppearance="?android:attr/textAppearanceMedium" /> <CheckBox android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView3" android:text="CheckBox" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/checkBox1" android:text="Radio Button Preference" android:textAppearance="?android:attr/textAppearanceMedium" /> <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView4"> <RadioButton android:id="@+id/radio0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="RadioButton" /> <RadioButton android:id="@+id/radio1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton" /> <RadioButton android:id="@+id/radio2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton" /> </RadioGroup> <Button android:id="@+id/save" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/radioGroup1" android:text="Save" /> <Button android:id="@+id/close" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/save" android:layout_alignBottom="@+id/save" android:layout_toRightOf="@+id/save" android:text="Cancel" /> </RelativeLayout>
Custom Preferences without PreferenceActivity - Preferences4.java
package com.as400samplecode; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; public class Preferences4 extends Activity { private EditText prefEditText; private CheckBox prefCheckbox; private RadioGroup prefRadioGroup; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.custom_pref); SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE); prefEditText = (EditText) findViewById(R.id.editText1); prefEditText.setText(customSharedPreference.getString("myEditTextPref", "")); prefCheckbox = (CheckBox) findViewById(R.id.checkBox1); prefCheckbox.setChecked(customSharedPreference.getBoolean("myCheckBoxPref", false)); prefRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1); RadioButton radioButton0 = (RadioButton) findViewById(R.id.radio0); prefRadioGroup.check(customSharedPreference.getInt("myRadioGroupPref",radioButton0.getId())); Button mClose = (Button)findViewById(R.id.close); mClose.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); Button mSave = (Button)findViewById(R.id.save); mSave.setOnClickListener(new OnClickListener() { public void onClick(View v) { savePreferences(); finish(); } }); } private void savePreferences(){ SharedPreferences customSharedPreference = getSharedPreferences("myCustomSharedPrefs", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = customSharedPreference.edit(); editor.putString("myEditTextPref", prefEditText.getText().toString()); editor.putBoolean("myCheckBoxPref",prefCheckbox.isChecked()); editor.putInt("myRadioGroupPref", prefRadioGroup.getCheckedRadioButtonId()); editor.commit(); RadioButton radioButton = (RadioButton) findViewById(prefRadioGroup.getCheckedRadioButtonId()); Log.v("Preferences:", "Radio Text: " + radioButton.getText()); } }
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.