-1

I'm trying to figure out why my items from my listview are displayed in a wrong order. I think this is related to the iterator but I'm not sure about that.

This is the code from my activity:

 //String Capitole
    String Articolul1 = getResources().getString(R.string.dispozitiiGeneraleArt_1);
    String Articolul2 = getResources().getString(R.string.dispozitiiGeneraleArt_2);
    String Articolul3 = getResources().getString(R.string.dispozitiiGeneraleArt_3);

    //ListView Set

    ListView listDispGen = (ListView) findViewById(R.id.dispozitiigeneralelist);

    HashMap<String, String> articolExplicatii = new HashMap<>();
    articolExplicatii.put(" Art.1", Articolul1);
    articolExplicatii.put(" Art.2", Articolul2);
    articolExplicatii.put(" Art.3", Articolul3);

    List<HashMap<String, String>> listItems = new ArrayList<>();
    SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.dispgeneralelist,
            new String[]{"First Line", "Second Line"},
            new int[]{R.id.main_item, R.id.sub_item});

    Iterator it = articolExplicatii.entrySet().iterator();

    while(it.hasNext()) {
        HashMap<String, String> resultsMap = new HashMap<>();
        Map.Entry pair = (Map.Entry)it.next();
        resultsMap.put("First Line", pair.getKey().toString());
        resultsMap.put("Second Line", pair.getValue().toString());
        listItems.add(resultsMap);
    }
    listDispGen.setAdapter(adapter);

The main problem is that when I'm running the app the items are not displayed in the correct order like: Art.1, Art.2....Art.9 but they are displayed random like Art.3, Art.1, Art.3 etc.

A_P
  • 331
  • 3
  • 15
BugaIulian
  • 315
  • 3
  • 18

1 Answers1

0

Use TreeMap that implemented SortedMap, it will maintain the order of insertion

Selvin
  • 6,598
  • 3
  • 37
  • 43
Galalen
  • 64
  • 1
  • 7
  • 1
    Hi Mohammed, thanks for taking the time to answer! It's good practice when supplying links in an answer to summarize their content or otherwise illustrate your point in the event that the link stops working in the future. Additionally, it appears that the link you provided is currently 404'd. Welcome to the community! – nukeforum Jul 31 '17 at 17:25
  • Also how TreeMap can be used as Adapter source? there is no built-in Adapter's implementation which is using the TreemMap – Selvin Jul 31 '17 at 17:27
  • Oh sorry i just pasted it wrong, And there is no bult-in adapter so building you own will help you solve you problem see this link: https://stackoverflow.com/questions/32569709/inflate-listview-with-treemap-data-custom-adapter And this is the previous one: https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html – Galalen Jul 31 '17 at 17:55