几乎在每个应用程序中,用户都首次登录,而下次打开该应用程序时,他会直接进入该应用程序而无需身份验证。因此,我试图在我的应用程序中创建完全相同的功能,我按照文档进行了编码,并编码到我的应用程序中。构建成功,但无法正常工作,在关闭应用程序后不断要求进行身份验证。
代码
package abc.xyz;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button b;
SharedPreferences sp;
EditText username,password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.button);
username = (EditText)findViewById(R.id.editText);
password = (EditText)findViewById(R.id.editText2);
sp = getSharedPreferences("b", MODE_PRIVATE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
if(sp.getBoolean("Logged",false)){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
}
});
}
public void login(){
String user=username.getText().toString().trim();
String pass=password.getText().toString().trim();
if(user.equals("admin")&& pass.equals("admin"))
{
sp.edit().putBoolean("Logged", true).apply();
Toast.makeText(this,"Success!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}else {
Toast.makeText(this,"username and password do not matched!",Toast.LENGTH_LONG).show();
}
}
}
有人可以帮我吗?
答案 0 :(得分:2)
您将状态保存为true
,那么每次执行登录方法时,您都需要在值为MainActivity2
时移至true
,因此使用
// move to next activity if user is authenticated
if(sp.getBoolean("Logged",false)){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
}
});
注意:如@shb所述,区分大小写很重要
答案 1 :(得分:1)
您要保存
sp.edit().putBoolean("Logged", true).apply();
带有大写字母'L'//已记录
但是在检索时,您使用的是小写字母'l'//已记录
if(sp.getBoolean("logged",false)){
//...
}
在两个地方都使用“已记录”或“已记录”。