Remove items from adapter/arraylist in for loop, preserving order of items

492 views Asked by At

I am having a pretty difficult situation which I just can`t find a solution for.

I have a sections recyclerview which I fill with data through an arraylist, this data contains URL links and normal text.

The normal text should be set as a section in the recyclerview and the URLs as the items. The tricky part is that the arraylist needs to be in a specific order with the sections.

So the recylcerview should look like this for example:

URL
Section 1
URL
URL
Section 2
URL
URL
URL
URL
Section 3
etc...

I first tried to modify (remove) items from the arraylist itself but it won`t work as the sections and URLs are then out of order as they should be.

I then thought to load the whole list into the recylerview and before showing it remove the relevant items (marked as dummy in below code) from the SimpleAdapter but this doesn`t work in a for loop.

So how can I remove the dummy items from the adapter or arraylist without losing the order of the sections and URLs shown in the recylcerview?

In below code I fill the arraylist and set the sections.

public static List<String> test = new ArrayList<>();
int k = 0;

for (String str : Arrays.asList(lines)) {
    str = unescapeJavaString(String.valueOf(Html.fromHtml(str)));

    if (!str.contains("some info")) {

     // if it is a URL add to arraylist, otherwise set section at relevant position in adapter.
     if (str.startsWith("http")) {
       test.add(k, str);
    } else {
      sections.add(new SimpleSectionedRecyclerViewAdapter.Section(k, str));
      test.add(k, "dummy"); // add dummy which should be removed.
    }
    k++;
  }
}

Removing it from the adapter, does not work either:

int i = 0;
  ...
mAdapter = new SimpleAdapter(this, sCheeseStrings, userID, dlTypeValue);
  ...
recyclerView.setAdapter(mSectionedAdapter);

        Iterator itr = test.iterator();
            String strElement = "";
            while (itr.hasNext()) {
                i++;
                strElement = (String) itr.next();
                if (strElement.equals("dummy")) {
                    mAdapter.remove(i);
                    mAdapter.notifyItemRemoved(i);
              }
         }
0

There are 0 answers