TimeToEnjoy
TimeToEnjoy

Reputation: 47

simple example of using SharedPreferences

I want email and password to be saved on SharedPreferences so that they can resume after the close of the application. I do not understand where is the error, the data after the close of the application are not set on EditText.

MainActivity.java

    public class MainActivity extends Activity {
    Session session;
    EditText email, password;
    Button save;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            email=(EditText) this.findViewById(R.id.editText1);
            password=(EditText) this.findViewById(R.id.editText2);
            save=(Button) this.findViewById(R.id.button1);
            session = new Session();
            if(session.getEmail()!=null){
                email.setText(session.getEmail());
                password.setText(session.getPassword());
            }
            save.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    session.saveData(getApplicationContext(), 
                            email.getText().toString(), password.getText().toString());
                }
            });
        }
    }

Session.java

public class Session {
    SharedPreferences prefs;
    Editor editor;
    Context context;
    public static String FIRST_TIME="true";
    public static String NAME_PREFS="MY_PREFS";
    public static String EMAIL="";
    public static String PASSWORD="";

    public void saveData(Context context, String email, String password){
        this.context=context;
        prefs= context.getSharedPreferences(NAME_PREFS, Context.MODE_PRIVATE);
        editor=prefs.edit();
        editor.putString(FIRST_TIME, "false");
        editor.commit();
        editor.putString(EMAIL, email);
        editor.putString(PASSWORD,password);
        editor.commit();
    }
    public String getEmail(){
        return prefs.getString(EMAIL, null);
    }
    public String getPassword(){
        return prefs.getString(PASSWORD, null);
    }
}

Upvotes: 1

Views: 121

Answers (1)

Pararth
Pararth

Reputation: 8134

The EMAIL and PASSWORD are supposed to be your keys so pass some string which will act as an identifier - the key for storing your value. Change it like:

  public static String EMAIL="saved_email";
    public static String PASSWORD="saved_password";  

Also, when you retrieve the values from prefs, need to initialize the same, eg. pass context in the getEmail() function:

public String getEmail(Context context){
SharedPreferences prefs = context.getSharedPreferences(NAME_PREFS, Context.MODE_PRIVATE);
return prefs.getString(EMAIL, null);
}

Upvotes: 2

Related Questions