1

目前我的应用程序正在“设备”表中搜索现有设备以启用登录访问。但是,我希望每次需要登录时都注册一个新设备,并在每次运行应用程序时让它们绕过登录页面。目前,该应用程序表示由于未正确保存用户名和密码,因此在打开时无效凭据。我该如何解决这个问题?移动应用程序共享首选项保存和调用用户登录

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

回答

2

为了节省登录凭据,我们应始终遵循下列代码: - 公共静态最后弦乐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(); 

我认为你必须使用的东西在你的代码而不是适用()甲基

+0

对不起,我还是相当新的这一点,我将此到setOnClickListener? – Lotse

+0

当您想要保存凭证时必须应用它。 –