|
|
|
Android Preferences กับ Shared Preferences มีวิธีใช้ยังไงครับ |
|
|
|
|
|
|
|
ตัวอย่าง UserHelper.java
Code (Java)
public class UserHelper {
Context context;
SharedPreferences sharedPerfs;
Editor editor;
// Prefs Keys
static String perfsName = "UserHelper";
static int perfsMode = 0;
public UserHelper(Context context) {
this.context = context;
this.sharedPerfs = this.context.getSharedPreferences(perfsName, perfsMode);
this.editor = sharedPerfs.edit();
}
public void createSession(String key) {
editor.putBoolean("isLogin", true);
editor.putString("userID", key);
editor.commit();
}
public void deleteSession() {
editor.clear();
editor.commit();
}
public boolean isLogin() {
return sharedPerfs.getBoolean("isLogin", false);
}
public String getUserID() {
return sharedPerfs.getString("userID", null);
}
}
วิธีใช้
Code (Java)
UserHelper usrHelper = new UserHelper(this);
// Create Session
usrHelper.createSession(ID);
// Delete Session
usrHelper.deleteSession();
// Check Login
if (usrHelper.isLogin()) {
} else {
}
// Get UserID
usrHelper.getUserID()
|
|
|
|
|
Date :
2013-02-08 22:38:54 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
แบบง่าย ๆ และสั้น ๆ
เก็บค่า(Android-Java)
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("sUsername",txtUsername.getText().toString());
editor.putString("sPassword",txtPassword.getText().toString());
editor.commit();
่อ่านค่า(Android-Java)
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
string strUsername = settings.getString("sUsername", "").toString();
string strPassword = settings.getString("sPassword", "").toString();
|
|
|
|
|
Date :
2014-04-09 13:44:47 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Android Shared Preferences (Session) : Create key/value in Application
|
|
|
|
|
Date :
2016-04-17 21:42:55 |
By :
mr.win |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 01
|