问题
Currently my application is searching for an existing device in "Device" table to enable login access. However, I want to register a new device every time they're required to log in and have them bypass the login page every time the application runs. Currently, the application says there's invalid credentials upon opening since the username and password aren't being saved properly. How do I solve this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// declaring variables
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword= (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
etIpAddress = (EditText) findViewById(R.id.etIpAddress);
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String ipAddress = etIpAddress.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (sharedPreferences.contains("ip")) {
performLogin(username, password, sharedPreferences.getString("ip", ipAddress));
}
// setting up things for login button
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String ipAddress = etIpAddress.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
sharedPreferences.edit()
.putString("ip", ipAddress)
.apply();
String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();
performLogin(username, password, ipAddress);
}
});
}
private void performLogin(String username, String password, String ipAddress) {
try {
Device.login(username, password, ipAddress, this);
} catch (JSONException e) {
onLoginFailure(e);
}
}
回答1:
For saving login credentials we always follow these code:- public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "ip";
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(ip, e);
editor.commit();
I think you must use that thing in your code rather then apply() meth
来源:https://stackoverflow.com/questions/37696925/mobile-application-shared-preferences-saving-and-calling-user-login