Wednesday, 23 November 2011

SharedPreferences in eazy way

Its very easy to use SharedPreferences in our application. we can also do this steps through model wise.  for that we need to create one Preferences class with getter & setter. And initialized variable in strings.xml for storing the values.
Lets take an example of saving the user name and user id in SharedPreferences.
strings.xml

<string name="uname">user name</string>
<string name="uid">emp id</string>
<string name="prefSettings"> Pref Settings</string>
<string>
now create SharedPreferences class named Store

/*
 * This class store the application service related data.
 * Whether to enable or disable the Application Service
 */

public class Store {
   
    private SharedPreferences settingsPreference;
    private Context context;
   
    /**
     * Create the application Shared Preference.
     * @param context To access the Android System.
     */
   
    public Store(Context context) {
        this.context = context;
        settingsPreference = context.getSharedPreferences(context.getString(R.string.prefSettings),      Context.MODE_PRIVATE);
         }
   
public boolean setValues(String userName, int uID)
{
try {
            final SharedPreferences.Editor settingsEditor = settingsPreference.edit();
            settingsEditor.putString(context.getString(R.string.uname), userName);
            settingsEditor.putInt(context.getString(R.string.uid), uID);
            settingsEditor.commit();
            return true;

}
              catch (Exception e) {
               e.printStackTrace();
              return false;
        }
    }

public String getUserName() {
        return settingsPreference.getString(context.getString(R.string.uname), null);
    }

public int getUID() {
        return settingsPreference.getString(context.getString(R.string.uid), 0);
    }
}

Now we need to only create the object of Store class from any where in your application and with the use of setter method set the value and with the help of getter get the value.

Ex: new Store(MyActivity.this).setValues("jack", 101);
       int id =  new Store(MyActivity.this).getUID();