0

i am making an application in which i want to implement login. i am saving user password in SharedPreference, it stored properly and works well. but when i force close the application the preference key got cleared. i am saving the key in the following code when user press the okey button.

case R.id.bOkey:
            if (sp.contains(KEY_PASSWORD)) {
                Toast.makeText(getApplicationContext(), "contains the key", Toast.LENGTH_LONG).show();
                if (sp.getString(KEY_PASSWORD, null).equals(etPassword.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_LONG).show();
                }
            }else{
                Toast.makeText(getApplicationContext(), "Does not contains the key", Toast.LENGTH_LONG).show();
                sp.edit().putString(KEY_PASSWORD, etPassword.getText().toString()).commit();
            }
            break;

Thanks in Advance!! -Usman Riaz-

Usman Riaz
  • 2,920
  • 10
  • 43
  • 66
  • I read somewhere that chained sharedPreferences are not (always) working, try not to chain them – Marko Niciforovic Aug 02 '13 at 15:33
  • Chained means ? ? @MarkoNiciforovic – Usman Riaz Aug 02 '13 at 15:35
  • It doesn't answer your question, but for security reasons you really shouldn't be saving the user's password to SharedPreferences as cleartext. You should, at least, encrypt it otherwise the users password may become compromised. – Mark Allison Aug 02 '13 at 15:37
  • sp.edit().putString(key,key).commit(); should be all in new lines. also if that fails try http://stackoverflow.com/questions/15353900/shared-preferences-reset-data-when-app-is-force-closed-or-device-is-restarted or http://stackoverflow.com/questions/11480871/sharedpreferences-being-reset-after-force-close or http://stackoverflow.com/questions/4801074/shared-preferences-reset-when-the-app-is-force-closed-or-crashes – Marko Niciforovic Aug 02 '13 at 15:38

1 Answers1

0

You should save Persistent Data also onPause() because You're totally sure that your app will switch to onPause state before closed..
So Morale is "always save your data on onPause() method".

Tizianoreica
  • 2,142
  • 3
  • 28
  • 43