我试图检查我的已保存ArrayList是否为空。当我运行这段代码时:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = this.getIntent();
String title = intent.getStringExtra(NotePad.EXTRA_MESSAGE);
notes.add(title);
Log.d("testt", "notes: " + notes);
if(title != null) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(notes);
editor.putString(Key, json);
editor.apply();
Log.d("ans", "notes: " + notes);
}
int t = CheckSharedPreferences();
Log.d("testt","t: "+t);
}
int CheckSharedPreferences() {
ArrayList<String> test = new ArrayList<String>();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Gson gson = new Gson();
String json = prefs.getString(Key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
test = gson.fromJson(json, type);
Log.d("testt", "test " + test);
if(test == null) {
return 1;
} else {
return 0;
}
}
即使列表为空,该方法始终返回0
。
这是日志中的一小段:
10-10 01:12:38.254 19365-19365/com.example.quicknote D/testt: notes: [null]
10-10 01:12:38.281 19365-19365/com.example.quicknote D/testt: test[null]
10-10 01:12:38.281 19365-19365/com.example.quicknote D/testt: t: 0
String s = null
,那么s
变量不持有空字符串,而是引用了null
。要持有空字符串,你需要写类似于String s = "";
的代码,因为这样的字符串存在但不包含任何字符,所以可以被认为是空的。同样,在你的情况下,if(test == null)
并不检查test
是否持有空列表,而是检查它是否持有null
,而不是任何列表。你想要的可能是if(test.isEmpty())
。 - Pshemo