我有一个具有以下活动流程A-> B-> C的应用程序。在活动C中,为用户提供了选择选项,以保存我存储在SharedPreferences文件中的用户名和数据(字符串和转换为字符串的字符串数组)并调用Intent.FLAG_ACTIVITY_CLEAR_TOP。这将它们带回活动A。但是,当我尝试检查存储的用户名与现在输入的用户名时,总是出现NullPointerException。
private void saveData(){
SharedPreferences session_data = getSharedPreferences("SESSION_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = session_data.edit();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < myData.length; i++) {
sb.append(myData[i]).append(",");
}
editor.putString("SAVED_SCAN",sb.toString());
editor.putString("SAVED_ID",myID);
Toast.makeText(C.this,"Data Saved",Toast.LENGTH_LONG).show();
endActivity();
}
private void endActivity(){
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
然后回到活动A。(textData是EditText.getText()。toString())
SharedPreferences prf = getSharedPreferences("SESSION_DATA",MODE_PRIVATE);
String testID = prf.getString("SAVED_ID",null);
try {
if(testID.equals(textData)){
toast.makeText(A.this,"MATCH",Toast.LENGTH_LONG).show();
}
} catch (NullPointerException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
将数据添加到共享首选项中:
SharedPreferences.Editor editor = getSharedPreferences("MY_PREFS_NAME",MODE_PRIVATE).edit();
editor.putString("name", "myname");
editor.putInt("id", 12);
editor.apply()
从共享首选项中获取数据:
SharedPreferences prefs = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE);
String name= prefs.getString("name", "xyz"); // here xyz is the default value
int id = prefs.getInt("id", 0); // 0 is the default value.