這是你如何保存用戶的詳細信息,當用戶登錄成功。
此外,如果您想在共享首選項中爲用戶下次登錄屏幕時製作用戶名,此代碼將對您有所幫助。
我還包括代碼來填充EditText中的共享prefernces值,如果方向更改。
//Form Variables
EditText userName;
CheckBox chkRememberMe;
//SharedPrefernces Variables to save userName and password of User
SharedPreferences loginPreferences;
private static final String SPF_NAME = "vidslogin";
private static final String USERNAME = "username";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Getting Values from edit text fields
userName = (EditText) findViewById(R.id.login_et_username);
//Check box to remember UN and PSW
chkRememberMe = (CheckBox) findViewById(R.id.cb_rememberMe);
//Read previously saved userName from sharedPreferences and populate in the editText
loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
userName.setText(loginPreferences.getString(USERNAME, ""));
}
//Saving Activity State
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//Read previously saved userName & password from sharedPreferences
loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
userName.setText(loginPreferences.getString(USERNAME, ""));
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
//Read previously saved userName & password from sharedPreferences
loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
userName.setText(loginPreferences.getString(USERNAME, ""));
}
}
// login function
public void login(){
//Check if he is authenticated
// if Authenticated and if the user checks "REMEMBER ME"-- Checkbox, save his details
//Saving userName into SharedPreferences to read for next time
String strUserName = userName.getText().toString().trim();
if (chkRememberMe.isChecked()){
loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().putString(USERNAME, strUserName).commit();
}
}
希望能得到。
你可以請你的代碼如何初始化偏好? – 2014-11-04 09:40:41
是的只需一分鐘 – Andrew 2014-11-04 09:47:39