I have a login form with a checkbox to let the app remember the email in LoginActivity. If I press the Log in button the email should be stored in SharedPreferences using the class AppPreferences.
The app remembers the email if I return to home screen by pressing home button and by pressing back.
But if I force close the app shows the default value as defined in the Preferencemanager.getString("value", "default_value"); method.
I have tried a lot of things people suggested on SO, but unfortunately none of the solutions worked. I even tried to solve it by putting all the SharedPreferences code in a separate class (see this question).
Below I put as much code relevant to the question. So both the classes LoginActivity and AppPreferences. There is no error message given by LogCat.
At both the Samsung devices I9100 and P3110 with Android 4.2.2 Cyanogenmod 10.1 and several different emulators this problem occurs. (I read some Samsung S devices with HoneyComb could't save SharedPreferences properly?)
EDIT:
As I forgot to mention, the project is targeted to API 17 and the minSdkVersion = 11. I only save credentials on click of Log in button.
EDIT 2: This problem also occurs if phone reboots
the LoginActivity class:
public class LoginActivity extends Activity
{
private static final String PREF_REMEMBER_EMAIL = "LoginCredentialsRememberEmail";
private static final String PREF_EMAIL = "LoginCredentialsEmail";
private String mEmail;
private EditText mEmailView;
private CheckBox cbRememberEmail;
private AppPreferences appPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
appPreferences = new AppPreferences(LoginActivity.this);
loadUserCredentials();
}
#Override
protected void onResume() {
super.onResume();
loadUserCredentials();
}
#Override
protected void onStart() {
super.onStart();
loadUserCredentials();
}
private void loadUserCredentials() {
String rememberEmail = appPreferences.getPreferenceString(PREF_REMEMBER_EMAIL);
String email = appPreferences.getPreferenceString(PREF_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText((rememberEmail == "1") ? email : "");
cbRememberEmail = (CheckBox) findViewById(R.id.cbRememberEmail);
cbRememberEmail.setChecked(rememberEmail == "1" ? true : false);
mEmail = mPassword = "";
}
private void saveUserCredentials() {
try {
String rememberemail = (((CheckBox) findViewById(R.id.cbRememberEmail)).isChecked()) ? "1" : "0";
appPreferences.setPreferenceString(PREF_REMEMBER_EMAIL, rememberemail);
String email = (rememberemail == "1") ? mEmail : "";
appPreferences.setPreferenceString(PREF_EMAIL, email);
}
public void cbRememberEmailClick(View view) {
boolean checked = ((CheckBox) findViewById(R.id.cbRememberEmail)).isChecked();
if (checked) {
new AlertDialog.Builder(this).setTitle(R.string.remember_email_notification_title).setMessage(R.string.remember_email_notification_message).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((CheckBox) findViewById(R.id.cbRememberEmail)).setChecked(true);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
((CheckBox) findViewById(R.id.cbRememberEmail)).setChecked(false);
}
}).show();
}
}
// ...
}
The AppPreferences class:
public class AppPreferences {
Context context;
private SharedPreferences settings = null;
private static String LOGIN_CREDENTIALS = "com.example.login.credentials";
private static String DEFAULT_STRING = "";
public AppPreferences(Context context) {
this.context = context;
settings = PreferenceManager.getDefaultSharedPreferences(context);
}
private String getKey(String key) {
return LOGIN_CREDENTIALS + "." + key;
}
public String getPreferenceString(String key) {
return settings.getString(getKey(key), DEFAULT_STRING);
}
public void setPreferenceString(String key, String value) throws Exception {
SharedPreferences.Editor editor = settings.edit();
editor.putString(getKey(key), (String) value);
editor.commit();
}
// ...
}
Any help is really appreciated, I'm stuck at this for days and it's really frustrating now.
Thanks in advance.
Dediqated
You don't show the code that calls saveUserCredentials. You should call it in onPause:
#Override
protected void onPause() {
super.onPause();
saveUserCredentials();
}
If you call it in one of the later lifecycle methods (such as onDestroy), it won't be called if the app is force-closed while in the background. (You can defer this to onStop if you are targeting only Honeycomb and later.)
i fixed it by changing the field rememberEmail to a Boolean instead of a string containing a 1 or 0. I dont know why this didn't work but I'm happier about the fact that after 11 days of frustration this is no issue anymore.
Also did I delete all the preference files in folder /data/data/com.example/shared_prefs/
changed code in LoginActivity
// ....
private void loadUserCredentials() {
Boolean rememberEmail = appPreferences.getPreferenceBoolean(PREF_REMEMBER_EMAIL);
String email = appPreferences.getPreferenceString(PREF_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(rememberEmail ? email : "");
cbRememberEmail = (CheckBox) findViewById(R.id.cbRememberEmail);
cbRememberEmail.setChecked(rememberEmail);
}
private void saveUserCredentials() {
try {
Boolean rememberEmail = ((CheckBox) findViewById(R.id.cbRememberEmail)).isChecked();
appPreferences.setPreferenceBoolean(PREF_REMEMBER_EMAIL, rememberEmail);
String email = (rememberEmail) ? mEmail : "";
appPreferences.setPreferenceString(PREF_EMAIL, email);
}
// ....
and in AppPreferences
// ....
private String getKey(String key) {
key = key.toLowerCase();
return LOGIN_CREDENTIALS + "." + key;
}
// newly added methods below
public String getPreferenceBoolean(String key) {
return settings.getBoolean(getKey(key), DEFAULT_BOOLEAN);
}
public void setPreferenceBoolean(String key, Boolean value) throws Exception {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(getKey(key), (Boolean) value);
editor.commit();
}
// ....
I hope you won't make the same mistake as I did ;)
I'd recommend you, putting the save method into the onDestroy method
If you are calling saveUserCredentials(); when ever checkbox is checked,This should work perfectly.Also try to initialise preference obj on start of application
Related
I have been searching for the correct answer everywhere, but couldn't find it anywhere. That is why I am posting this question, this may look very similar to other questions but I didn't find the answer to this yet. I have to retrieve the user data that was saved during the login on Android device and I want to use the same data in a fragment, I tried using several answers found on StackOverflow, none of them worked for me. Look at the code below, how can I get the user values into strings?
SharedPreferences preferences = getActivity().getSharedPreferences("mysharedpref",Context.MODE_PRIVATE);
String user_name = preferences.getString("user_id",null);
String password = preferences.getString("role", null);
I have to pass these string values to a URL, but it doesn't work. I also checked passing values manually, it's working. For example, if I take assign values to the above strings like
String user_name="admin";
String password="administrator";
Best way to use your SharedPrefernce is by using your appContext that is accessible to the whole App(Common SharedPrefernce and accessible Everywhere).
Define your SharedPrefernce instance in your Application class with get and set methods as below : (If you have not created the Application class then create one as below, This class is called at the start of your app)
public class Application extends android.app.Application {
private static Application _instance;
private static SharedPreferences _preferences;
#Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public static Application get() {
return _instance;
}
/**
* Gets shared preferences.
*
* #return the shared preferences
*/
public static SharedPreferences getSharedPreferences() {
if (_preferences == null)
_preferences = PreferenceManager.getDefaultSharedPreferences(_instance);
return _preferences;
}
//set methods
public static void setPreferences(String key, String value) {
getSharedPreferences().edit().putString(key, value).commit();
}
public static void setPreferences(String key, long value) {
getSharedPreferences().edit().putLong(key, value).commit();
}
public static void setPreferences(String key, int value) {
getSharedPreferences().edit().putInt(key, value).commit();
}
public static void setPreferencesBoolean(String key, boolean value) {
getSharedPreferences().edit().putBoolean(key, value).commit();
}
//get methods
public static String getPrefranceData(String key) {
return getSharedPreferences().getString(key, "");
}
public static int getPrefranceDataInt(String key) {
return getSharedPreferences().getInt(key, 0);
}
public static boolean getPrefranceDataBoolean(String key) {
return getSharedPreferences().getBoolean(key, false);
}
public static long getPrefranceDataLong(String interval) {
return getSharedPreferences().getLong(interval, 0);
}
}
Declare the Application class in AndroidManifest.xml file with line android:name=".Application" as shown in below snippet:
<application
android:name=".Application"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Now, How to store key-value:
Application.setPreferences("Key","String_Value");
How to fetch key-value:
String value_string=Application.getPrefranceData("Key");
You can now set-SharedPrefernce key-value and get-SharedPrefernce value from anywhere in the app using public Application class and the static get and set methods
Firstly create a SharedPreference.java Class.
public class SharedPreference {
Context context;
SharedPreferences sharedPreferences;
String user_name;
String password;
public SharedPreference(Context co) {
context = co;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getPassword() {
password = getStringInput("password");
return password;
}
public void setPassword(String password) {
this.password = password;
stringInput("password", password);
}
public String getUser_name() {
user_name = getStringInput("Username");
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
stringInput("Username", user_name);
}
public void stringInput(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public String getStringInput(String key) {
return sharedPreferences.getString(key, "0");
}
}
Now go into activity or Fragment
example: I'm gone use it in MainActivity.java
public class MainActivity extends AppCompatActivity {
Prefrences prefrences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Dashboard");
prefrences = new Prefrences(MainActivity.this);
prefrences.setUser_name("Rishabh Jain");
prefrences.setUser_name("8369554235");
Log.e("Details",prefrences.getUser_name()+" "+prefrences.getPassword())
}
}
The output will be Rishabh Jain 8369554235.
Similarly, you can use this in any Activity or any Fragment
I guess you are trying to get values with different key. Get values with same key you put them with.
String user_name = preferences.getString(preferences.KEY_USERNAME,null);
String password = preferences.getString(preferences.KEY_PASSWORD, null);
----BUT----
And don't use singleton pattern for SharedPreferences it is very bad to use Context in singleton. It will crash your app. You can figure it out why.
Instead use static methods.
public class PreferenceUtil {
public static final String PASSWORD = "PASSWORD";
public static void setInt(Context context, int in, String key) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
editor.putInt(key, in);
editor.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences settings;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(key)) {
return settings.getInt(key, 0);
} else
return 0;
}
}
And access it like this
int password = PreferenceUtil.getInt(getActivity(), PreferenceUtil.PASSWORD);
I have shared prefs to be used throughout my app but right now only four activities. The first activity is a recyclerview with checkboxes and the checked status is saved (in the recycler adapter) for each checkbox using a shared prefs helper class. The next activity is then launched as a tablayout with fragments containing a list of random items.
When the user clicks any of these items in the second activity's fragment, a third activity is launched. Here, I try to retrieve the values from the shared prefs helper class but it returns null, same situation in fourth activity too. Also, when I back press twice to first activity, it also returns null.
I would post my code for all activities but that would just make the question lengthy. Here's my helper class:
public class WalpyPrefsHelper {
public Context context;
public SharedPreferences customizePrefs, tabsCountPrefs;
public SharedPreferences.Editor editor, tabsEditor;
public static final String CUSTOMIZE_TABS_PREFS = "customizeTabsPrefs";
public static final String COUNT_TABS_PREFS = "countTabsPrefs";
public static final String KEY_NATURE = "nature";
public static final String KEY_SPACE = "space";
public static final String KEY_SEASONS = "seasons";
public static final String KEY_ART = "art";
public static final String KEY_SCIFI = "sci_fi";
public static final String KEY_MISC = "misc";
public static final String KEY_COUNT = "count_tabs";
public WalpyPrefsHelper(Context context) {
this.context = context;
customizePrefs = context.getSharedPreferences(CUSTOMIZE_TABS_PREFS, Context.MODE_PRIVATE);
editor = customizePrefs.edit();
tabsCountPrefs = context.getSharedPreferences(COUNT_TABS_PREFS, Context.MODE_PRIVATE);
tabsEditor = tabsCountPrefs.edit();
}
public void saveNaturePrefs(String s){
editor.putString(KEY_NATURE, s).apply();
}
public String getKeyNature(){
return customizePrefs.getString(KEY_NATURE, null);
}
public void removeNaturePrefs(){
editor.remove(KEY_NATURE).apply();
}
public void saveSpacePrefs(String s){
editor.putString(KEY_SPACE, s).apply();
}
public String getKeySpace(){
return customizePrefs.getString(KEY_SPACE, null);
}
public void removeSpacePrefs(){
editor.remove(KEY_SPACE).apply();
}
public void saveSeasonsPrefs(String s){
editor.putString(KEY_SEASONS, s).apply();
}
public String getKeySeasons(){
return customizePrefs.getString(KEY_SEASONS, null);
}
public void removeSeasonPrefs(){
editor.remove(KEY_SEASONS).apply();
}
public void saveArtPrefs(String s){
editor.putString(KEY_ART, s).apply();
}
public String getKeyArt(){
return customizePrefs.getString(KEY_ART, null);
}
public void removeArtPrefs(){
editor.remove(KEY_ART).apply();
}
public void saveSci_FiPrefs(String s){
editor.putString(KEY_SCIFI, s).apply();
}
public String getKeyScifi(){
return customizePrefs.getString(KEY_SCIFI, null);
}
public void removeSci_FiPrefs(){
editor.remove(KEY_SCIFI).apply();
}
public void saveMiscPrefs(String s){
editor.putString(KEY_MISC, s).apply();
}
public String getKeyMisc(){
return customizePrefs.getString(KEY_MISC, null);
}
public void removeMiscPrefs(){
editor.remove(KEY_MISC).apply();
}
public void removeAllPrefs(){
editor.remove(KEY_NATURE).apply();
editor.remove(KEY_SPACE).apply();
editor.remove(KEY_SEASONS).apply();
editor.remove(KEY_ART).apply();
editor.remove(KEY_SCIFI).apply();
editor.remove(KEY_MISC).apply();
}
public void saveCount(int count) {
tabsEditor.putInt(KEY_COUNT, count).apply();
}
public int getSaveCount(){
return tabsCountPrefs.getInt(KEY_COUNT, 0);
}
}
The preferences are saved in first activity recycler adapter like below snippet:
viewholder.customizeSelImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nature, space, seasons, art, scifi, misc;
switch (position) {
case 0:
nature = prefsHelper.getKeyNature();
if (viewholder.customiseCheckBox.isChecked()) {
viewholder.customiseCheckBox.setChecked(false);
viewholder.customiseCheckBox.setVisibility(View.INVISIBLE);
if (nature != null) {
prefsHelper.removeNaturePrefs(); // infer nullity
if (count > 0) {
count--;
Log.d(TAG, "Count Value:\t" + count);
}
Log.d(TAG, "Position:\t" + position + " is UNChecked");
}
} else {
viewholder.customiseCheckBox.setChecked(true);
viewholder.customiseCheckBox.setVisibility(View.VISIBLE);
count ++;
Log.d(TAG, "Count Value:\t" + count);
prefsHelper.saveNaturePrefs(Constants.NATURE); // save value. Works fine
Log.d(TAG, "Position:\t" + position + " is Checked");
}
break;
In next activity, I am able to retrieve the shared prefs values like below snippet:
String space = prefsHelper.getKeySpace();
String nature = prefsHelper.getKeyNature();
String seasons = prefsHelper.getKeySeasons();
String art = prefsHelper.getKeyArt();
String scifi = prefsHelper.getKeyScifi();
String misc = prefsHelper.getKeyMisc();
after initializing like this: prefsHelper = new WalpyPrefsHelper(this); but in third and fourth activities, those strings above return null values.
----Edited Part---
Second Activity Where Prefs Are Used:
public void setUpTabs() {
prefsHelper = new WalpyPrefsHelper(this);
int count = prefsHelper.getSaveCount();
Log.d(TAG, "Tabs Count:\t" + count);
setUpViewPager(viewPager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
space = prefsHelper.getKeySpace();
nature = prefsHelper.getKeyNature();
seasons = prefsHelper.getKeySeasons();
art = prefsHelper.getKeyArt();
scifi = prefsHelper.getKeyScifi();
misc = prefsHelper.getKeyMisc();
pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager(), this);
pagerAdapter.addTab(new Top30Fragment(), Constants.Top30);
if (nature != null) {
pagerAdapter.addTab(new NatureFragment(), Constants.NATURE);
}
if(space != null){
pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);
}
if (seasons != null){
pagerAdapter.addTab(new SeasonsFragment(), Constants.SEASONS);
}
if (art != null){
pagerAdapter.addTab(new ArtFragment(), Constants.ART);
}
if (scifi != null){
pagerAdapter.addTab(new SciFiFragment(), Constants.SCI_FI);
}
if (misc != null){
pagerAdapter.addTab(new MiscFragment(), Constants.MISC);
}
pagerAdapter.addTabAtLastPosition(new PrefsFragment(), Constants.PREFS);
viewPager.setAdapter(pagerAdapter);
}
I have used shared prefs to set the tablayout at app install time but after navigating other activities and back to this, those tabs from prefs are removed, in other scenarios, my last tab then contains the view and data of the nature fragment from prefs.
In adapter and last two activities in sequence, I am getting the key like this but it returns null:
prefsHelper = new WalpyPrefsHelper(this);
Log.d(TAG, "Nature Key:\t" + prefsHelper.getKeyNature());
Also, in the adapter, the value returns null and in other subsequent activities after the second activity. Is this sharedprefs behavior, I have misconfigured somewhere or sharedprefs can't be passed from activity to fragment and adapter context?
I have tried .apply() and .commit() for the editor but same situation occurs.
Anyone understands why? Thanks.
I have fixed this problem by using sqlite to persist and retrieve the values.
Looking at the attached code flow, I could not find any problematic parts. Although each activity has a preference manager class instance created and used, the SharedPrefenrece object itself is shared as one object, so that is not a problem.
Please check again whether the preference value is deleted or not in the flow.
Also, if you attach the part that uses prefsHelper in each activity, troubleshooting will be helpful.
I have two Activities. And a static integer called as counter.
So if I press a button in activity 'A' then counter = counter + 1.
Here is the code from activity a:
public static int counter = 0;
cmdOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
if (counter == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
And here it is from activity b :
cmdSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a.counter = a.counter + 1;
if (a.counter == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
My problem is when i tried to press a button from activity a 3 times it work perfectly. So the values are 3 now.
But when i tried press a button from activity b, the value is going restart into 0. Actually i didn't destroy activity a.
So what i want is the value is going continouosly even i press from activity a or b.
Any ideas ?
Edited :
I have edit the code. Tagihan activity is what im trying to accomplished. So when the counter is 5, then tagihan activity is changing.
Dont use static data, this is a bad approach and is not a common OOP-way to develope, instead try passing data between activities...
Act1
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
Act2:
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Android development web is giving an introduction to this:
http://developer.android.com/training/basics/firstapp/starting-activity.html
After your edit, I can see that you need a "global varfiable" that can be read/write for all the activities:
Solution:
All activities are embedded in an Application, so if you habe fields/members in the application you can access to them with a stadard setter/getter
you need:
Define an application
public class MyApplication extends Application {
private int counterVariable;
public int counterVariable() {
return this.counterVariable;
}
public void setCounterVariable(int someVariable) {
this.counterVariable = someVariable;
}
}
add the App to the manifest:
<application
android:name="MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
Then in your activities get and set the variable like so:
// cast to Application and call the setter
((MyApplication) this.getApplication()).counterVariable(1);
// cast to Application and call the getter
int counter = ((MyApplication) this.getApplication()).getCounterVariable ();
Please use the below code:
// Generalized form of Avoiding the Static value holding:
public class SPDataHandler {
private Context mContext;
private SharedPreferences mPreference;
public SPDataHandler(Context context) {
this.mContext = context;
this.mPreference = mContext.getSharedPreferences("SAMPLE_SP", Context.MODE_PRIVATE);
}
/**
* COMMON SETTER FOR INTEGER DATA
*/
private void setIntegerData(String key, int value) {
SharedPreferences.Editor editor = mPreference.edit();
editor.putInt(key, value);
editor.commit();
}
/**
* COMMON GETTER FOR INTEGER SP DATA
*/
private int getIntegerSpData(String key, int defaultValue) {
return this.mPreference.getInt(key, defaultValue);
}
// Your Getter and Setter
public int getmCount() {
return this.getIntegerSpData("Count", 1);
}
public void setmCount(int cont) {
this.setIntegerData("Count", cont);
}
}
// Your Activity A
SPDataHandler handler = new SPDataHandler(this);
int count = handler.getmCount();
cmdOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = count + 1;
handler.setmCount(count); // Change the logic based on your requirement
if (count == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
// Your Activity B
SPDataHandler handler = new SPDataHandler(this);
int count = handler.getmCount();
cmdSuccess.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count = count + 1;
handler.setmCount(count); // Change the logic based on your requirement
if (count == 5)
{
tagihan.txtShip1.setTextColor(Color.parseColor("#000000"));
tagihan.txtNilai1.setTextColor(Color.parseColor("#000000"));
tagihan.txtSupir1.setTextColor(Color.parseColor("#000000"));
}
}
I currently have a service that loads preferences upon startup, stores them as fields, then registers an OnSharedPreferenceChangeListener to update the fields when a preference is modified. Currently, my code looks like this:
public class MyService extends Service {
private int _prefA;
private boolean _prefB;
private String _prefC;
private boolean _prefD;
private SharedPreferences _preferences;
private SharedPreferences.OnSharedPreferenceChangeListener _prefChangeListener;
#Override
public void onCreate() {
super.onCreate();
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_prefA = Integer.parseInt(_preferences.getString(PREF_A_KEY, "0"));
_prefB = _preferences.getBoolean(PREF_B_KEY, false);
_prefC = _preferences.getString(PREF_C_KEY, null);
_prefD = _preferences.getBoolean(PREF_D_KEY, false);
_prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(PREF_A_KEY)) {
_prefA = Integer.parseInt(sharedPreferences.getString(key, "0"));
} else if (key.equals(PREF_B_KEY)) {
_prefB = sharedPreferences.getBoolean(key, false);
} else if (key.equals(PREF_C_KEY)) {
_prefC = sharedPreferences.getString(key, null);
} else if (key.equals(PREF_D_KEY)) {
_prefD = sharedPreferences.getBoolean(key, false);
}
}
};
_preferences.registerOnSharedPreferenceChangeListener(_prefChangeListener);
}
}
It works as expected, but adding more preferences is becoming tedious, since I have to update the code in both onCreate() and OnSharedPreferenceChangeListener. Is there any way to change this so that the code to load the preferences only needs to be written once?
This is rather ideal. However, it reduced the overhead a little:
Create initializer functions:
private void initializeAccounts() {
...
Resources res = getResources();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String User = preferences.getString(res.getString(R.string.username), null);
String Pass = preferences.getString(res.getString(R.string.password), null);
...
}
And then group the preferences :
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (getString(R.string.prefkey_password).equals(key) || getString(R.string.prefkey_username).equals(key)) {
initializeAccounts();
}
}
In the onCreate:
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
initializeAccounts();
}
The reason why I group the preferences together is that the other preferences don't change when I edit one of them. However, when I for instance want to change the password of my account, I also require the other preferences like username or the server URI to reconnect to the server. So, it more or less doesn't matter if I reset them.
Hope this helps.
Hi i have a class (MyCustomForm.xml) which i use as a LoginForm for the user.
Now i want to save and load the value from the username(EditText) from the LoginForm using SharedPreferences but i do not know how to set the value of username saved by SharedPreferences into the EditText in LoginForm(MyCustomForm.xml).
I was thinking to save the value in OnPause in my Main.xml and load the value through OnCreate in the class MyCustomForm.xml
Generaly i would like to use SharedPreferences globaly.
How would this look like?
Can somebody please help me to get on the right track?
It was thinking something like this Main.xml:
public class AndroidLogin extends Activity implements OnClickListener {
#Override
protected void onPause() {
super.onPause();
Editor e = mPrefs.edit();
e.putString(USERNM, username);
e.commit();
}
}
Code MyCustomForm (LoginForm):
public class MyCustomForm extends Dialog {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
userTest.setText(USERNM);
}
}
You can do something like this :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(YouActivity.this);
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
server.setText(servername); // EditText
And you store data like this :
SharedPreferences.Editor editor = settings.edit();
editor.putString("server", "serverName");
EDIT :
This piece of code should do the trick for you :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
String servername = settings.getString("sharedPreferencesKey", "defaultValue");
You need to use the Prefs & Editor
SharedPreferences spOptions;
SharedPreferences.Editor spOptionEditor;
spOptions = getSharedPreferences("yourKey", 0);
spOptionEditor = spOptions.edit();
string username = spOptions.getString("USERNM", null)
null represents the default value if you don't have anything stored yet
You store the data like this:
spOptionEditor.putString("USERNM", txtUsername.getText().toString());
spOptionEditor.commit();
Generally I would recommend you to save the username on a valid login, and not in any lifecycle method.
Then change myForm to this:
public class MyCustomForm extends Dialog {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
String s = getContext().getSharedPreferences("prefName", Mode.PRIVATE).getString(USERNM);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
userTest.setText(s);
}
}
public void sharedPrefernces() {
sh_Pref = getSharedPreferences("Login Credentials", MODE_PRIVATE);
toEdit = sh_Pref.edit();
toEdit.putString("Username", username);
toEdit.putString("Password", password);
toEdit.commit();
}
Read more: http://mrbool.com/how-to-implement-shared-preferences-in-android/28370#ixzz34ymRp6mN
Just create a file called preferences... and store the value to it using different methods.
Use the methods people have suggested to put and get data from them...
public class Settings extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
public static final String PREFS_PRIVATE = "PREFS_PRIVATE";
public static final String MASTERKEY = "!##$%^&*";
public static final String KEYA = "KEYA";
public static final String KEYB = "KEYB";
public static final String KEYC = "KEYC";
--- the create and get methods for getting and sharing data in the prefs... .....
public static void createPreference(Context context){
getPrefs(context).edit().putString(KEYA, "Default");
getPrefs(context).edit().putInt(KEYB, 0);
getPrefs(context).edit().putLong(KEYC, 0);
getPrefs(context).edit().putBoolean(KEYD, false);
getPrefs(context).edit().commit();
}
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(PREFS_PRIVATE, 0);
}
public static String getUsername(Context context) {
getPrefs(context).getString(USERNAME, "default");
}
public static void setUsername(Context context, String value) {
getPrefs(context).edit().putString(USERNAME, value).commit();
}
}
..... so on and so forth..... Just implement it if you find any doubt or any thing that you need in more specific please let me know.