要检查ArrayList是否为空

问题描述 投票:1回答:4

我正在尝试检查保存的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
java android list collections sharedpreferences
4个回答
1
投票

似乎正在检查您的日志

test = gson.fromJson(json, type);

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

您必须检查以下三个条件:

if ( test == null || test.isEmpty() || test.get(0) == null ) { return 1;}

0
投票

[test永远不会是null,因为您之前已经向该变量分配了一个对象:ArrayList<String> test = new ArrayList<String>();

改为尝试:if(test.isEmpty())


0
投票

尝试用test.isEmpty()代替test == null


0
投票

或者,您可能还想通过.size()方法进行检查。不为空的列表的大小将大于零

if (test.size()>0){
//execute your code
}
© www.soinside.com 2019 - 2024. All rights reserved.