1

I would like to retrieve the values ​​saved in the shared preferences in one activity to use these values ​​in another activity. I know that the values ​​saved in the shared preferences are usable in all the activities of the app. Anyone know how I could do? Thanks in advance to everyone! This is the code for saving shared preferences in my MenuActivity:

private final String DefaultEmailValue = ""; private String email; private final String DefaultUsernameValue = ""; private String userName; private static final String PREFS_NAME = "preferences"; private static final String PREF_EMAIL = "Email"; private static final String PREF_USERNAME = "Username"; private void savePreferences() { SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); // Edit and commit email = mEmail.getText().toString(); userName = mUsername.getText().toString(); System.out.println("onPause save email: " + email); System.out.println("onPause save username: " + userName); editor.putString(PREF_EMAIL, email); editor.putString(PREF_USERNAME, userName); editor.commit(); } private void loadPreferences() { SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // Get value email = settings.getString(PREF_EMAIL, DefaultEmailValue); userName = settings.getString(PREF_USERNAME, DefaultUsernameValue); mEmail.setText(email); mUsername.setText(userName); System.out.println("onResume load email: " + email); System.out.println("onResume load username: " + userName); } 

2 Answers 2

2

You already know method. You got field from Preferences in one activity.

You can get field value in another activity with same method as before.

SharedPreferences prefs = this.getSharedPreferences("preferences", Context.MODE_PRIVATE); String email = prefs .getString("Email", ""); 
Sign up to request clarification or add additional context in comments.

7 Comments

So I should make public: static final String PREF_EMAIL = "Email"; so it could be visible in another activity and use it like first argument in getString?
yes, if you don't want make it public, you need to copy define and paste it to another activity.
thank you very much mate, and for the second argument in getString() what could I use?
it's default value, if you didn't save email address before, getString() returns default value. So you could use null or empty string or default email address.
yes, SharedPreference saved data to file in internal storage. So you can save your email in SharedPreference.
|
0

You save your values to SharedPreferences by name. Just retrieve needed value by name on other Activity. SharedPreferences is a storage for your app, not only for Activity. You can retrieve data from any place where you can instantiate SharedPreference instance.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.