On Android, SharedPreferences
is a good way of doing that, it's quite simple. But a friendly reminder... THIS IS NOT THE SAFEST WAY but it's probably the easiest one. The user could access that file if the device is rooted, and the data is stored in plain text in a Key-Value
way.
You could try to use some encryption on that data, or try to find a wrapper to handle that, like SecurePreferences
as it was suggested in other answers. iOS should have other wrappers or methods as well.
You could also use the AccountManager
solution provided by Google. This was already discussed on this question here on SO.
You could also try to change the way you're authenticating the user on your server, a suggestion would be using OAuth
, like Twitter does.
But, if you like to use SharedPreferences
, there's more on that below.
You can read more about SharedPreferences
here. And you can access the docs here.
An example:
public class SessionManager {
private static SessionManager instance = null;
private SharedPreferences sharedPref;
private Editor editor;
private final String prefName = "session";
public static SessionManager getInstance() {
if (instance == null) {
instance = new SessionManager();
}
return instance;
}
private SessionManager() {
sharedPref = context_.getSharedPreferences(prefName,Context.MODE_PRIVATE);
}
public void saveUser(String username, String password, int sid) {
if (TextUtils.isEmpty(username) && TextUtils.isEmpty(password) && sid > 0) {
editor = sharedPref.edit();
editor.putInt("session_id",sid);
editor.putString("username", username);
editor.putString("password",password);
editor.commit();
}
}
public String getUsername() {
return sharedPref.getString("username",null);
}
// Declare other methods to fetch the rest of the data.
}
TL;DR: It's best not to store that sensitive data as plain text. But it's definitely the simplest way.