首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查ArrayList是否为空

检查ArrayList是否为空
EN

Stack Overflow用户
提问于 2019-10-09 19:54:07
回答 4查看 5.3K关注 0票数 3

在运行代码时,我试图检查保存的ArrayList是否为空:

代码语言:javascript
复制
  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

这些是来自日志的片段:

代码语言:javascript
复制
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
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-10-09 20:05:52

看上去你的日志

代码语言:javascript
复制
test = gson.fromJson(json, type);

返回一个以null作为第一个/唯一元素的列表。

您必须在以下情况下检查这三个条件:

代码语言:javascript
复制
if ( test == null || test.isEmpty() || test.get(0) == null ) { return 1;}
票数 3
EN

Stack Overflow用户

发布于 2019-10-09 19:58:59

尝试test.isEmpty()而不是test == null

票数 1
EN

Stack Overflow用户

发布于 2019-10-09 19:57:41

test从来不是null,因为您以前为这个变量分配了一个对象:ArrayList<String> test = new ArrayList<String>();

试一试:if(test.isEmpty())

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58311368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档