The easiest way to do that is to store user's name as keys and values inside a Shared Preferences file.
SharedPreferences - the right way
SharedPreferences provides easy way to store persist simple values on device's storage. We use it often to store some user's or application's preferences and share it between many places - like multiple Activities. (In your case, you want to store user's name and share it between multiple Activities).
Basically there are two main operations one can perform when using SharedPreferences in Android. That is store data and load data. You should:
- Create a new
SharedPreferences
object.
- Then get an
Editor
instance from that object. The Editor
object will help you manipulate the data that you’ve stored.
- Use
putString
, putBoolean
methods to store a pair key/value.
- Use getBoolean, getString to get the values you want.
Simply, use this custom method to save user's name:
private void savePreferences(String key, String value) {
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString(key, value);
editor.commit();
}
Example of use:
savePreferences("name", et.getText().toString());
Now you can retrieve user's name from preference in wherever activity you want. (Result
,Main
...)
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", null);
Hope I helped.
Happy Coding :D