Reputation: 51
I want to save a String value on Android and have access to this String every time the application starts.
For instance the String value will have the user's name which he has created on his own. And after restarting the app he would have this name already on the top. Like a cookie or something. How to save such file on android memory ?
Can someone guide me?
I used:
public class Login extends Activity
{
String user = null;
public String saveUserOnAndroid()
{
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", 0);
String savedUser = myPrefs.getString("user", null);
if(savedUser == null)
{
user = UUID.randomUUID().toString();
String hashedUser = md5(user);
SharedPreferences.Editor myPrefsEditor = myPrefs.edit();
myPrefsEditor.putString("user", hashedUser);
myPrefsEditor.commit();
return hashedUser;
}
else
return savedUser;
}
and it seems not to work well.
Upvotes: 1
Views: 978
Reputation: 30990
Well you didn't mention you're calling the saveUserOnAndroid()
method from another class. In this case:
public String saveUserOnAndroid(Context c) {
SharedPreferences myPrefs = c.getSharedPreferences("myPrefs", 0);
String savedUser = myPrefs.getString("user", null);
if(savedUser == null) {
user = UUID.randomUUID().toString();
String hashedUser = md5(user);
SharedPreferences.Editor myPrefsEditor = myPrefs.edit();
myPrefsEditor.putString("user", hashedUser);
myPrefsEditor.commit();
return hashedUser;
} else {
return savedUser;
}
}
And when calling this method, don't forget to supply it the required Context
and you should be okay.
Upvotes: 1
Reputation: 1
You have to do it:
public static final String mypref="mypref";
public static String Username="";
@Override
public void OnCreate(Bundle ic){
super.OnCreate(ic);
setContentView(R.layout.main);
SharedPreference sh = getSharedPreference(mypref, 0);
Username = sh.getString("User", Username);
}
public void onPause(){
super.onPause();
SharedPreference sh = getSharedPreference(mypref, 0);
SharedPreference.Editor editor = sh.edit();
editor.putString("User", Username);
}
Upvotes: 0
Reputation: 234795
There are several options, described here. I recommend using SharedPreferences.
Upvotes: 0