所以我试图在我的主要活动之前弹出一个登录或注册页面。我的后端工作但共享首选项将无法访问,即使正确的值在运行时存储在对象中。
这是我尝试读取值的主要片段
sharedPreferences = getSharedPreferences("app",MODE_PRIVATE);
if(sharedPreferences.getString("logged","false").equals("false")){
Intent intentMain = new Intent(getApplicationContext(), Registration.class);
startActivity(intentMain);
finish();
}
这是我的登录组件:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
textViewRegisterNow = findViewById(R.id.registerText);
textInputEditTextPassword = findViewById(R.id.password);
textInputEditTextEmail = findViewById(R.id.email);
textViewError = findViewById(R.id.error);
progressBar = findViewById(R.id.loading);
sharedPreferences = getSharedPreferences("app", MODE_PRIVATE);
if(sharedPreferences.getString("logged","false").equals("true")){
Intent intentMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intentMain);
finish();
}
buttonSubmit = findViewById(R.id.submit);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
textViewError.setVisibility(View.GONE);
email = textInputEditTextEmail.getText().toString();
password = textInputEditTextPassword.getText().toString();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url ="";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if(status.equals("success")){
name = jsonObject.getString("name");
email = jsonObject.getString("email");
apiKey = jsonObject.getString("apiKey");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("logged,", "true");
editor.putString("name,", name);
editor.putString("email,", email);
editor.putString("apiKey,", apiKey);
editor.apply();
Intent intentMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intentMain);
finish();
}else{
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
textViewError.setText(error.getLocalizedMessage());
textViewError.setVisibility(View.VISIBLE);
}
}){
protected Map<String, String> getParams(){
Map<String, String> paramV = new HashMap<>();
paramV.put("email", email);
paramV.put("password", password);
return paramV;
}
};
queue.add(stringRequest);
}
});
我几乎浏览了这里的每一个线程,但没有任何效果。有人有想法吗?
您必须使用与保存时使用的密钥完全相同的密钥来获取保存的值。
在这里你保存它使用
editor.putString("logged,", "true");
并且密钥被记录,以逗号结尾。
在这里你可以使用它
sharedPreferences.getString("logged","false");
密钥是logged没有逗号。
你必须像下面这样改变它:
sharedPreferences.getString("logged,","false");
最好避免使用硬编码密钥来防止出现此类错误。有道理吗?