Programatt
Programatt

Reputation: 836

Shared preferences not working correctly

I'm trying to store some strings in a shared preference file and then retrieve them in another activity, except it doesn't seem to be working. Any guidance as to where im going wrong would be much appreciated. Many thanks.

public void save(View view) {
    SavePreferences("name", nameS);
    SavePreferences("current", currentS);
    SavePreferences("goal", goalS);
    SavePreferences("CurrentBmi", cBmiS);
    SavePreferences("goalBmi", gBmiS);
    Toast.makeText(this, "profile Saved", Toast.LENGTH_SHORT).show();
    startActivity(new Intent(this, MainActivity.class));

}

private void SavePreferences(String key, String value) {
    SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}






 public class Progress extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_progress);
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    String test = sharedPreferences.getString("name", "");
    String test2 = sharedPreferences.getString("current", "");
    TextView testy = (TextView) findViewById(R.id.textView1);
    testy.setText(test);
    TextView testz = (TextView) findViewById(R.id.test2);
    testz.setText(test2);
}

Upvotes: 2

Views: 2687

Answers (1)

Tarun
Tarun

Reputation: 13808

With the code you have you are limiting the access of sharedpreferences to activity(context) level.

Values saved in activity Activity MainActivity will not be available in activity Progress since you are using getPreferences(MODE_PRIVATE);

Change this to

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

or

SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

getPreferences:

public SharedPreferences getPreferences (int mode)

Retrieve a SharedPreferences object for accessing preferences that are private to this activity.

Upvotes: 4

Related Questions