Android共享首选项声明默认值

时间:2016-06-05 10:07:57

标签: android android-studio sharedpreferences

所以我在onCreate函数中声明默认值“ipAddress”时遇到了一个小问题。 ipAddress在底部void中声明,但不用于检查ip是否存在。这是我正在使用的代码:

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

    });
}

1 个答案:

答案 0 :(得分:0)

在您的代码中进行此更改

..
setContentView(R.layout.activity_login);

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

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