I made a small project where i try to change the name from edit text using share preference.Here is my code
SharePreferenceOwnActivity.java
public class SharePreferenceOwnActivity extends Activity {
Button b1;
TextView t1;
/** Called when the activity is first created. */@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.b1);
t1 = (TextView) findViewById(R.id.t1);
LoadPreferences();
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
Intent intent = new Intent().setClass(SharePreferenceOwnActivity.this, SharepreferenceActivity.class);
startActivity(intent);
}
});
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
t1.setText(strSavedMem1);
}
}
SharepreferenceActivity.java
public class SharepreferenceActivity extends Activity {
EditText e1;
Button b2;
/** Called when the activity is first created. */@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
e1 = (EditText) findViewById(R.id.e1);
b2 = (Button) findViewById(R.id.b2);
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SavePreferences("MEM1", e1.getText().toString());
Intent intent = new Intent().setClass(SharepreferenceActivity.this, SharePreferenceOwnActivity.class);
startActivity(intent);
}
});
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
Here the edit text doesnot change the textview. 🙁 why? I did not get the error
You have problem in following statement.
As per Google Doc
So the Error you have done is
you are setting preference in Preference Object which is private to
SharepreferenceActivityAnd
you are trying to read from Preference Object which is private to
SharePreferenceOwnActivitySo solution is
Replace
By
In Both Activities.