-1

I want to add a new item to my arrayadapter and then for it to render in my view. After digging online, I noticed that the ArrayAdapter class keeps its own version of the arraylist as mentioned here: Android ListView not refreshing after notifyDataSetChanged.

Heres my code:

The add new item code:

public void addRecordSet(View view) {

    RecordStats recordStats = new RecordStats();
    recordStats.RecordID = mRecord.id;

    long recordStatId = mDatabaseHelper.addRecordStats(recordStats);
    recordStats.ID = (int) recordStatId;

    recordStatsList.add(recordStats);
    mAdapter.swapRecordFormList(recordStatsList);
}

The arrayadapter code:

    public void swapRecordFormList(ArrayList<RecordStats> recordStatsList) {
        mRecordStatsList = recordStatsList;
        notifyDataSetChanged();
    }

However, i get this error:

Process: com.example.andyxu.enzo3, PID: 19289

java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
    at java.util.ArrayList.get(ArrayList.java:437)

Any ideas?

EDIT:

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View recordForm = convertView;
    if (recordForm == null) {
        recordForm = LayoutInflater.from(mContext).inflate(R.layout.custom_record_form, parent, false);
    }

    RecordStats currentRecord = mRecordStatsList.get(position);

    EditText reps = (EditText) recordForm.findViewById(R.id.reps);
    if (currentRecord.Reps > 0) {
        reps.setText(String.valueOf(currentRecord.Reps));
    }

    EditText weight = (EditText) recordForm.findViewById(R.id.weight);
    if (currentRecord.Weight > 0) {
        weight.setText(String.valueOf(currentRecord.Weight));
    }
    return recordForm;
}
anderish
  • 1,709
  • 6
  • 25
  • 58

1 Answers1

1

ArrayAdapter can be backed by a live list object that you provide. (So the link you referenced is not quite relevant to your situation). With an ArrayAdapter all you need to do is call add on the backing list object and then call notifyDataSetChanged.

List<String> list = new ArrayList<>();
ArrayAdapter<String> adatper = new ArrayAdapter<String>(this, android.R.layout.layout, list);
listView.setAdapter(adapter);

list.add("Another item");
adapter.notifyDataSetChanged();
jspcal
  • 50,847
  • 7
  • 72
  • 76