We can save user information local to the application using shared preferences. This information persist till the application is install in your device.
public class MySharedPreference {
private static MySharedPreference mInstance=null;
private static final String PREFS_NAME = "MY_PREFS";
private static String PREFS_USER_KEY = "PREFS_USER_NAME";
SharedPreferences mSharedPreferences=null;
SharedPreferences.Editor editor=null;
public MySharedPreference(Context context) {
this.mSharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
this.editor = mSharedPreferences.edit();
}
public static MySharedPreference getInstance(Context context){
if(context!=null) {
if (mInstance == null) {
mInstance = new MySharedPreference(context);
}
}
return mInstance;
}
public String getUserSharedPref() {
return this.mSharedPreferences.getString(PREFS_USER_KEY,null);
}
public void setUserSharedPref(String userName) {
editor.putString(PREFS_USER_KEY, userName);
editor.commit();
}
}
//******************************************************************//
Save your preferences-
MySharedPreference mPref= MySharedPreference.getInstance(context);
mPref.setUserSharedPref(userName.getText().toString());
//*****************************************************************//
Get Preference Value-
String str= MySharedPreference.getInstance(context).getUserSharedPref();
No comments:
Post a Comment