john c :
I'm having trouble getting my sharedpreferences to work. I'm trying to load in data from a textbox in another activity into a textview. I don't get any errors, but it keeps returning the default value of "nameKey".
Here is where the data is being entered and saved
public class ActivitySettings extends AppCompatActivity {
SharedPreferences sharedPreferences;
final String MyPREFERENCES = "MyPrefs";
final String Name = "nameKey";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final EditText enterName1 = (EditText) findViewById(R.id.enterName1);
final EditText enterName2 = (EditText) findViewById(R.id.enterName2);
Button btnOK = (Button) findViewById(R.id.btnOK);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
btnOK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String n = enterName1.getText().toString();
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Name, n);
editor.commit();
}
});
and here's a different activity where i'm trying to read in the data and set it to a textview
public class ActivityDuel extends AppCompatActivity {
public String getPrefs(String n, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString(n, "nameKey");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duel);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView txtD1 = (TextView) findViewById(R.id.txtD1);
txtD1.setText(getPrefs("name", this));
}
}
Sajith :
Call like this
txtD1.setText(getPrefs("nameKey", this));
And your getPrefs()
function should like below
public String getPrefs(String n, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString(n, "");
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=327950&siteId=1