Reputation: 95
I am trying to set preference for a string value as:
//onCreate
if(name==null){
setprefer();
}
else{
getpref();
}
private void setprefer() {
et1 = (EditText) findViewById(R.id.editText1);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
s = et1.getText().toString();
if(s.matches(""))
{
//wait!!
Toast.makeText(Home.this, "Enter your name", Toast.LENGTH_SHORT).show();
}
else{
setpref(s);
Intent i = new Intent(Home.this, Homescreen.class);
i.putExtra("name", s);
startActivity(i);
Home.this.finish();
}
}
});
}
private void setpref(String name) {
SharedPreferences pref = this.getSharedPreferences("prefkey", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("key", name);
editor.commit();
}
private void getpref() {
SharedPreferences prefs = this.getSharedPreferences("prefkey", Context.MODE_PRIVATE);
s = prefs.getString("key", name);
Intent i = new Intent(Home.this, Homescreen.class);
i.putExtra("name", name);
startActivity(i);
Home.this.finish();
}
I am setting the preference with the method setprefer() but each time i start my activity its asks fr the name which i have already stored in my preference. Somehow i am not able to get my saved prefereces in the above code. Please suggest a fix.
Upvotes: 0
Views: 111
Reputation: 6014
Shared preference has a method called contains().Try that to check if shared preference already exists or not. That method will return true if the preference exists.
Upvotes: 0
Reputation: 8023
This depends on what name
has when you do this :
if(name==null){
setprefer();
}
else{
getpref();
}
But since before checking you are not assigning any value to name
variable, it's null and hence setPrefer()
is called each time. You'll need to fetch the value from SharedPrefs and assign in to name
before checking for name == null
.
Upvotes: 1