我已经厌倦了使用sharedpreference来存储会话,并使用Log来测试是否存储了信息。但是,android studio似乎跳过了涉及共享偏好的代码。我做错了吗?
全局
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String EmployeeID = "employeeID";
public static final String EmployeeName = "employeeName";
SharedPreferences sharedpreferences;
的OnCreate
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String user = sharedpreferences.getString("EmployeeName", "");
if (user.equalsIgnoreCase("")) {
Log.i("Status", "No session detected");
} else {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
protected void onPostExecute(Employee results){
if (results != null){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(EmployeeID, results.getEmployeeID());
editor.putString(EmployeeName, results.getFirstName()+" "+results.getLastName());
editor.apply();
editor.commit();
Log.i("aaaaaaaa", "hellloooo"); // It print this libe
String a = sharedpreferences.getString("EmployeeID", "");
Log.i("aaaaaaaa", a); // but not this line
Toast.makeText(LoginActivity.this, " Authenticated", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
else {
Toast.makeText(LoginActivity.this, "Invalid ID", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:1)
尝试使用PreferenceManager.getDefaultSharedPreferences(context)
,看看是否能解决您的问题。它基本上是一回事,唯一的区别是你用这种方式写入默认的prefs文件。
答案 1 :(得分:0)
String a = sharedpreferences.getString("EmployeeID", "");
这可能只是修复bug但我会尝试使用常量值" public static final String EmployeeID =" employeeID&#34 ;;"代替。也许关键变量区分大小写?