Lotse Lotse - 6 months ago 55
Android Question

Android Studio SharedPreference Saving Login to Database

I want to save the the user's login details when they first login the mobile application into my Device table and have them bypass the login screen every time the application opens.

I think I've got that part going it's just saving the variables I'm not understanding. My question is how and where should I begin saving the user's detail?

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

// declaring variebles
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword= (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
etIpAddress = (EditText) findViewById(R.id.etIpAddress);
final String username = etUsername.getText().toString();
final 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);

String username = etUsername.getText().toString().trim();
String password = etPassword.getText().toString().trim();

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("ip", ipAddress);
editor.putString("username", username);
editor.putString("password", password);
editor.commit();

performLogin(username, password, ipAddress);
}
});
}

Answer

Here:

performLogin(username, password, sharedPreferences.getString("ip", ipAddress));

user getting login fail because both username and password is passing empty value to performLogin every-time when starting Activity.

In same way as getting ip also get username and password from SharedPreferences like:

if (sharedPreferences.contains("ip")) {
      String strUsername=sharedPreferences.getString("username", "");
      String strPassword=sharedPreferences.getString("password", "");
      String strIpAddress=sharedPreferences.getString("ip", ipAddress);
      performLogin(strUsername, strPassword,strIpAddress);
  }