Reputation: 793
I want to retrieve some values which ive saved to the sharedpreferences from one activity and want to call it in another.
Basically how can i get the name from the first activity and automatically display it in the field in the second activity?
So as an example i have this, which saves into the preferences.
public class Settings extends Activity {
EditText editText;
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new Button_Clicker());
loadSavedPreferences();
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String name = sharedPreferences.getString("name", "Your Name");
editText.setText(name);
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
class Button_Clicker implements Button.OnClickListener {
public void onClick(View v) {
savePreferences("name", editText.getText().toString());
finish();
}
}
}
Now i have another activity where i can use the value instead of it being typed again:
public class Details extends Activity {
EditText nameText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
nameText = (EditText) findViewById(R.id.nameText);
Button button = (Button) findViewById(R.id.calculate);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
Upvotes: 1
Views: 11977
Reputation: 5336
One of the nice things about the SharedPreference
class is that it is designed to be available to any Activity
within you application. You can retrieve any SharedPreference
with two simple calls:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String desiredPreference = sharedPreferences.getString("NameOfSharedPreference", "DefaultValue");
While it may seem obvious make sure that you have actually created and stored the data you wish to save before you try and retrieve it. To continue on the example above, use the following code snippet to store your data into SharedPreferences
:
Editor editor = sharedPreferences.edit();
editor.putString("NameOfSharedPreference", "ValueToStore");
editor.commit();
Upvotes: 5
Reputation: 106
You can call "PreferenceManager.getDefaultSharedPreferences(context)" from any activity of your apps.
I think you have an error in your code :put "editText.setText(weight)" instead of editText.setText(name);
Upvotes: 1