To check if ArrayList is empty

Viewed 5005

I am trying to check if my saved ArrayList is empty or not when I run the code:

  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;
    }
}

This method always returns 0 even if the list is empty.

These is snippet from a log:

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
4 Answers

Checking your logs, it seems

test = gson.fromJson(json, type);

returns a list with null as first/only element.

you must check these three conditions inside if:

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

Try test.isEmpty() instead of test == null

test is never null, since you have assigned an object to this variable before: ArrayList<String> test = new ArrayList<String>();

Try this instead: if(test.isEmpty())

Alternatively, you may also want to check by the .size() method. The list that isn't empty will have a size more than zero

if (test.size()>0){
//execute your code
}
Related