0

in activity1 (emailpreferences), I take the email through an edittext. I would like to use this Email again on reopenning application

This is my code:

public  static final String MyPREFERENCES = "MyPref";
public static final String Email = "emailkey";
SharedPreferences sharedPreferences;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.emailpreferences);

    edit1=(EditText)findViewById(R.id.editText);
    buttonpref=(Button)findViewById(R.id.button);

    sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    buttonpref.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String email = edit1.getText().toString();

            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putString(Email, email);

But the email is not retrieved when the following is done:

public class MainActivity extends AppCompatActivity {

Text name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    String name = sharedPreferences.getString(Email, "email");
    Toast.makeText(this,name, Toast.LENGTH_LONG).show();
}
}
suku
  • 10,507
  • 16
  • 75
  • 120
stefan
  • 3
  • 1

2 Answers2

1

Firstly, you need a commit or apply command on your editor to assign the key to the value.

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Email, email);
editor.commit(); //or editor.apply();

PreferenceManager and SharedPreference are different. Please read on them. You retrieve the value this way.

SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name = sharedPreferences.getString(Email, "email");
suku
  • 10,507
  • 16
  • 75
  • 120
  • Finally i am able to store email from one activity to another. Thanks everyone for hints. – stefan Oct 10 '16 at 21:32
  • Welcome :), please mark the answer as correct. (There is a tick mark below the down vote button on the left of the answer) – suku Oct 10 '16 at 22:10
0

To store use this:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Email, email);
editor.apply();

To retrieve use this:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedEmail  = preferences.getString(Email, "email");

I would suggest you to make a utility class and create a funtion for storing and retreiving sharedPreferences so that you don't need to write this boilerplate code again and again.

Neeraj Jha
  • 123
  • 1
  • 8