在运行代码时,我试图检查保存的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发布于 2019-10-09 20:05:52
看上去你的日志
test = gson.fromJson(json, type);返回一个以null作为第一个/唯一元素的列表。
您必须在以下情况下检查这三个条件:
if ( test == null || test.isEmpty() || test.get(0) == null ) { return 1;}发布于 2019-10-09 19:58:59
尝试test.isEmpty()而不是test == null
发布于 2019-10-09 19:57:41
test从来不是null,因为您以前为这个变量分配了一个对象:ArrayList<String> test = new ArrayList<String>();
试一试:if(test.isEmpty())
https://stackoverflow.com/questions/58311368
复制相似问题