Search code examples
javaandroidlistviewandroid-arrayadapter

android ArrayAdapter.clear() clears custom method variable


I have a ListView with a custom `ArrayAdapter where I update sometimes the values sometimes. Everything works fine, but on the first update it becomes empty.

My array adapter:

protected class ResultArrayAdapter extends ArrayAdapter<JsonObject> {
    private ArrayList<JsonObject> values;
    protected ResultArrayAdapter(ArrayList<JsonObject> values) {
            super(context, R.layout.content_result_item, values);
            this.values = values;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) { ... }
    public void updateValues(ArrayList<JsonObject> values) {
        //here values.size() > 0 and everything OK
        this.clear();
        //here values.size() == 0, why??
        for (JsonObject value : values) {
            this.add(value);
        }
        this.notifyDataSetChanged();
    }
}

When I update my values, I call updateValues() and after calling this.clear(), also the parameter ArrayList<JsonObject> values of this method is empty. So after this, there is no value to add with this.add(value), but only after the first time of onUpdate().

Also renaming the ArrayList<JsonObject> values parameter, or saving it in another one, does not help.


Solution

  • It seems like you're updating the values with the same instance of the ArrayList you're setting with the constructor. You could surpass this by not setting the initial values from outside. Also you don't actually need the values member in your class.

    protected class ResultArrayAdapter extends ArrayAdapter<JsonObject> {
        protected ResultArrayAdapter(List<JsonObject> values) {
            super(context, R.layout.content_result_item, new ArrayList<JsonObject>());
            updateValues(values);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) { ... }
        public void updateValues(List<JsonObject> values) {
            this.clear();
            this.addAll(values);
            this.notifyDataSetChanged();
        }
    }
    

    Also you can use addAll() instead add() within a for loop and provide a List instead of an ArrayList. You could even choose Collection if you like.