1

I am facing problem in showing the preview of first letter in Android listview, when i do fast scroll i get the preview of text but it will be pointing to the wrong location in list.

For eg, please have a look at the below image, in this now we are in M section, still L letter is appearing.

enter image description here

Here is the Listadapter code, which implements the above Technic, any mistake in the code?

    class MyListAdaptor extends ArrayAdapter<String> implements
        SectionIndexer 
{

    HashMap<String, Integer> alphaIndexer;
    String[] sections;

    public MyListAdaptor(Context context, LinkedList<String> items) {
        super(context, R.layout.list_item, items);

        alphaIndexer = new HashMap<String, Integer>();
        int size = items.size();

        for (int x = 0; x < size; x++) {
            String s = items.get(x);

            // get the first letter of the store
            String ch = s.substring(0, 1);
            // convert to uppercase otherwise lowercase a -z will be sorted
            // after upper A-Z
            ch = ch.toUpperCase();

            // HashMap will prevent duplicates
            alphaIndexer.put(ch, x);
        }

        Set<String> sectionLetters = alphaIndexer.keySet();

        // create a list from the set to sort
        ArrayList<String> sectionList = new ArrayList<String>(
                sectionLetters);

        Collections.sort(sectionList);

        sections = new String[sectionList.size()];

        sectionList.toArray(sections);
    }

    public int getPositionForSection(int section) {
        return alphaIndexer.get(sections[section]);
    }

    public int getSectionForPosition(int position) {
        return 0;
    }

    public Object[] getSections() {
        return sections;
    }
}
Naruto
  • 9,476
  • 37
  • 118
  • 201

1 Answers1

4

By using alphaIndexer.put(ch, x); to prevent duplicates, you are keeping the last position for an element starting with ch instead of the first one. That is because each call to put other than the first with a given key will update the old value. Try with this code and you will be one step closer:

if( !alphaIndexer.containsKey(ch) )
    alphaIndexer.put(ch, x);
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • May i know the reason why, the appropriate letter is not getting displayed?, the code what i have posted is the correct way of implementing right? – Naruto May 19 '12 at 03:26
  • @LLL: Not really, you are working with characters as 1-lengthed strings, relaying on hashmap for uniqueness, and you certainly do things in a far fetched way... The correct section is being displayed (L) so you certainly messed up its position. Have you actually tried my suggestion? – K-ballo May 19 '12 at 03:32