I have 3 activities in my Gingerbread 2.3.3 application for Android which I'm constructing in Eclipse.
1) MainActivity
--- two options, go to LoginActivity or go directly to HomeScreenActivity
2) LoginActivity
--- Enter login credentials (aka username and password), validate, and then store in SharedPreferences. After successfully validating, it goes to the HomescreenActivity. Here's what I have for the SharedPreferences section in LoginActivity:
public static final String PREFS_FILE = "MY_PREFS";
SharedPreferences prefs = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("USERNAME", getUsername());
editor.putString("PASSWORD", getPassword());
editor.commit();
3) HomescreenActivity
--- a basic homescreen that shows who's logged in right now in the top right corner in a TextView. For this my onResume() contains:
public static final String PREFS_FILE = "MY_PREFS";
SharedPreferences prefs = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
TextView name_text = (TextView) findViewById(R.id.name_text_vw);
name_text.setText(prefs.getString("USERNAME", "");
When I use the LoginActivity
and login, I properly see the username in the TextView on the HomescreenActivity
. However, when I exit the application and do some other stuff to get the activity off the stack, I want to go back to the application, go directly to my HomescreenActivity
and see my username logged in already. But this doesn't happen. Does anyone know why? I thought SharedPreferences was the way to store settings and data even after you've left your application. Maybe I'm not using the correct mode -- aka MODE_WORLD_READABLE
or MODE_WORLD_WRITABLE
?
There are shared prefs for activities, and shared prefs for apps. Maybe you are using activity prefs.
To save to preferences:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL",
"myStringToSave").commit();
To get a stored preference:
PreferenceManager.getDefaultSharedPreferences(context).getString("MYLABEL",
"defaultStringIfNothingFound");
Where context is your Context.