Search This Blog

Monday, 19 March 2012

Chapter 23:public interface SharedPreferences


public interface

SharedPreferences

android.content.SharedPreferences

Class Overview

Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage.

Public Methods

public abstract boolean contains (String key)

Since: API Level 1
Checks whether the preferences contains a preference.
Parameters
key
The name of the preference to check.
Returns
  • Returns true if the preference exists in the preferences, otherwise false.

public abstract SharedPreferences.Editor edit ()

Since: API Level 1
Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
Note that you must call commit() to have any changes you perform in the Editor actually show up in the SharedPreferences.
Returns
  • Returns a new instance of the SharedPreferences.Editor interface, allowing you to modify the values in this SharedPreferences object.

public abstract Map<String, ?> getAll ()

Since: API Level 1
Retrieve all values from the preferences.
Returns
  • Returns a map containing a list of pairs key/value representing the preferences.
Throws
NullPointerException

public abstract boolean getBoolean (String key, boolean defValue)

Since: API Level 1
Retrieve a boolean value from the preferences.
Parameters
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
Returns
  • Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a boolean.
Throws
ClassCastException

public abstract float getFloat (String key, float defValue)

Since: API Level 1
Retrieve a float value from the preferences.
Parameters
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
Returns
  • Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a float.
Throws
ClassCastException

public abstract int getInt (String key, int defValue)

Since: API Level 1
Retrieve an int value from the preferences.
Parameters
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
Returns
  • Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not an int.
Throws
ClassCastException

public abstract long getLong (String key, long defValue)

Since: API Level 1
Retrieve a long value from the preferences.
Parameters
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
Returns
  • Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a long.
Throws
ClassCastException

public abstract String getString (String key, String defValue)

Since: API Level 1
Retrieve a String value from the preferences.
Parameters
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
Returns
  • Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a String.
Throws
ClassCastException

public abstract Set<String> getStringSet (String key, Set<String> defValues)

Since: API Level 11
Retrieve a set of String values from the preferences.
Parameters
key
The name of the preference to retrieve.
defValues
Values to return if this preference does not exist.
Returns
  • Returns the preference values if they exist, or defValues. Throws ClassCastException if there is a preference with this name that is not a Set.
Throws
ClassCastException

public abstract void registerOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)

Since: API Level 1
Registers a callback to be invoked when a change happens to a preference.
Parameters
listener
The callback that will run.
See Also

public abstract void unregisterOnSharedPreferenceChangeListener (SharedPreferences.OnSharedPreferenceChangeListener listener)

Since: API Level 1
Unregisters a previous callback.
Parameters
listener
The callback that should be unregistered.



Example of using SharedPreferences.Editor



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="@string/hello"
   />
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Saved Mem 1:"
   />
<TextView 
   android:id="@+id/savedmem1"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Saved Mem 2:"
   />
<TextView 
   android:id="@+id/savedmem2"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<EditText
   android:id="@+id/edittext1"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<Button
   android:id="@+id/save_mem1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Save Mem 1"
   />
<EditText
   android:id="@+id/edittext2"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<Button
   android:id="@+id/save_mem2"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Save Mem 2"
   />
</LinearLayout>


AndroidSharedPreferencesEditor.java
package com.exercise.AndroidSharedPreferencesEditor;
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.TextView;
public class AndroidSharedPreferencesEditor extends Activity {
EditText editText1, editText2;
TextView textSavedMem1, textSavedMem2;
Button buttonSaveMem1, buttonSaveMem2;
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       textSavedMem1 = (TextView)findViewById(R.id.savedmem1);
       textSavedMem2 = (TextView)findViewById(R.id.savedmem2);
       editText1 = (EditText)findViewById(R.id.edittext1);
       editText2 = (EditText)findViewById(R.id.edittext2);
       buttonSaveMem1 = (Button)findViewById(R.id.save_mem1);
       buttonSaveMem2 = (Button)findViewById(R.id.save_mem2);
      
       buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
       buttonSaveMem2.setOnClickListener(buttonSaveMem2OnClickListener);
      
       LoadPreferences();
   }
  
   Button.OnClickListener buttonSaveMem1OnClickListener
    = new Button.OnClickListener(){
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   SavePreferences("MEM1", editText1.getText().toString());
   LoadPreferences();
  }
   
   };
  
   Button.OnClickListener buttonSaveMem2OnClickListener
 = new Button.OnClickListener(){
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   SavePreferences("MEM2", editText2.getText().toString());
   LoadPreferences();
  }
   };
  
   private void SavePreferences(String key, String value){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
   }
  
   private void LoadPreferences(){
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    String strSavedMem1 = sharedPreferences.getString("MEM1", "");
    String strSavedMem2 = sharedPreferences.getString("MEM2", "");
    textSavedMem1.setText(strSavedMem1);
    textSavedMem2.setText(strSavedMem2);
   }
}












preferences.xml

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory
            android:title="@string/inline_preferences">
        <CheckBoxPreference
                android:key="checkbox_preference"
                android:title="@string/title_checkbox_preference"
                android:summary="@string/summary_checkbox_preference" />
    </PreferenceCategory>
    <PreferenceCategory
            android:title="@string/dialog_based_preferences">
        <EditTextPreference
                android:key="edittext_preference"
                android:title="@string/title_edittext_preference"
                android:summary="@string/summary_edittext_preference"
                android:dialogTitle="@string/dialog_title_edittext_preference" />
        <ListPreference
                android:key="list_preference"
                android:title="@string/title_list_preference"
                android:summary="@string/summary_list_preference"
                android:entries="@array/entries_list_preference"
                android:entryValues="@array/entryvalues_list_preference"
                android:dialogTitle="@string/dialog_title_list_preference" />
    </PreferenceCategory>
    <PreferenceCategory
            android:title="@string/launch_preferences">
        <!-- This PreferenceScreen tag serves as a screen break (similar to page break
             in word processing). Like for other preference types, we assign a key
             here so it is able to save and restore its instance state. -->
        <PreferenceScreen
                android:key="screen_preference"
                android:title="@string/title_screen_preference"
                android:summary="@string/summary_screen_preference">
            <!-- You can place more preferences here that will be shown on the next screen. -->
            <CheckBoxPreference
                    android:key="next_screen_checkbox_preference"
                    android:title="@string/title_next_screen_toggle_preference"
                    android:summary="@string/summary_next_screen_toggle_preference" />
        </PreferenceScreen>
        <PreferenceScreen
                android:title="@string/title_intent_preference"
                android:summary="@string/summary_intent_preference">
            <intent android:action="android.intent.action.VIEW"
                    android:data="http://www.android.com" />
        </PreferenceScreen>
    </PreferenceCategory>
    <PreferenceCategory
            android:title="@string/preference_attributes">
        <CheckBoxPreference
                android:key="parent_checkbox_preference"
                android:title="@string/title_parent_preference"
                android:summary="@string/summary_parent_preference" />
        <!-- The visual style of a child is defined by this styled theme attribute. -->
        <CheckBoxPreference
                android:key="child_checkbox_preference"
                android:dependency="parent_checkbox_preference"
                android:layout="?android:attr/preferenceLayoutChild"
                android:title="@string/title_child_preference"
                android:summary="@string/summary_child_preference" />
    </PreferenceCategory>
</PreferenceScreen>
Example
ShowSettingsActivity
package com.javacodegeeks.android.preferences; 

import android.app.Activity; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.preference.PreferenceManager; 
import android.widget.TextView; 

public class ShowSettingsActivity extends Activity { 

 @Override 
 protected void onCreate(Bundle savedInstanceState) { 

  super.onCreate(savedInstanceState); 
  setContentView(R.layout.show_settings_layout); 

  SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); 

  StringBuilder builder = new StringBuilder(); 

  builder.append("\n" + sharedPrefs.getBoolean("perform_updates", false)); 
  builder.append("\n" + sharedPrefs.getString("updates_interval", "-1")); 
  builder.append("\n" + sharedPrefs.getString("welcome_message", "NULL")); 

  TextView settingsTextView = (TextView) findViewById(R.id.settings_text_view); 
  settingsTextView.setText(builder.toString()); 

 } 

} 






QuickPrefsActivity

package com.javacodegeeks.android.preferences;

import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.Menu;
import android.view.MenuItem;

public class QuickPrefsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, ShowSettingsActivity.class));
return true;
}
return false;
}
}
preferences.xml
<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory
android:title="First Category"
android:key="first_category">
<CheckBoxPreference
android:key="perform_updates"
android:summary="Enable or disable data updates"
android:title="Enable updates"
android:defaultValue="true"
/>
<ListPreference
android:key="updates_interval"
android:title="Updates interval"
android:summary="Define how often updates will be performed"
android:defaultValue="1000"
android:entries="@array/updateInterval"
android:entryValues="@array/updateIntervalValues"
android:dependency="perform_updates"
/>
</PreferenceCategory>

<PreferenceCategory
android:title="Second Category"
android:key="second_category">

<EditTextPreference
android:key="welcome_message"
android:title="Welcome Message"
android:summary="Define the Welcome message to be shown"
android:dialogTitle="Welcome Message"
android:dialogMessage="Provide a message"
android:defaultValue="Default welcome message" />

</PreferenceCategory>
</PreferenceScreen>

array.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string-array name="updateInterval">
<item name="1000">Every 1 second</item>
<item name="5000">Every 5 seconds</item>
<item name="30000">Every 30 seconds</item>
<item name="60000">Every 1 minute</item>
<item name="300000">Every 5 minutes</item>
</string-array>
<string-array name="updateIntervalValues">
<item name="1000">1000</item>
<item name="5000">5000</item>
<item name="30000">30000</item>
<item name="60000">60000</item>
<item name="300000">300000</item>
</string-array>

</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javacodegeeks.android.preferences"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".QuickPrefsActivity" 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=".ShowSettingsActivity" />
</application>
<uses-sdk android:minSdkVersion="3" />

</manifest>
show_setting_layout

<?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:id="@+id/settings_text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

http://developer.android.com/reference/android/content/SharedPreferences.htmlssssssss

No comments:

Post a Comment