Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To check if ArrayList is empty

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
like image 738
shaswat kumar Avatar asked Jul 25 '26 11:07

shaswat kumar


1 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;}
like image 138
Bilal Siddiqui Avatar answered Jul 27 '26 03:07

Bilal Siddiqui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!