Lotse Lotse - 4 months ago 23
Android Question

Android Shared Preference Declaring Default Value

So I'm having a small issue with declaring the default value "ipAddress" in my onCreate function. ipAddress is declared in the bottom void but not for checking whether the ip exists. This is the code that I'm working with:

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

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
if (sharedPreferences.contains("ip")) {
performLogin(etUsername, etPassword, sharedPreferences.getString("ip", ipAddress));
}

// 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);

// 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);
}

});
}

Answer

make this change in your code

..
setContentView(R.layout.activity_login);

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

String ip=sharedPreferences.getString("ip",null);
if(ip!=null){
  performLogin(etUsername, etPassword, ip);
}