0

I have an adapter and i want to add a string to it but when i run this code it only add the last string in the songstoadd variable ... That is a custom adapter which adds dividers in where neccessary but in the Array Adapter i want to a all of the strings that have the same first letter in their name ....

SeparatedListAdapter adapter = new SeparatedListAdapter(this);
     ArrayList<String> songstoadd = new ArrayList<String>();

              Collections.sort(songtitle);
              int m = 0;
              while( m <songtitle.size()-1){
                  if(songtitle.get(m).substring(0, 1) == songtitle.get(m+1).substring(0, 1)){
                      m++;
                  }else{
                   songstoadd.clear();
                   songstoadd.add(songtitle.get(m));

                adapter.addSection(songtitle.get(m).substring(0, 1), new ArrayAdapter<String>(getApplicationContext(),R.layout.song, songstoadd));

              m++;
                  }



      }
              setListAdapter(adapter);

        }
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Waggoner_Keith
  • 590
  • 2
  • 9
  • 37

2 Answers2

1

Try this, And let me know what happen..

songstoadd.clear();
 while( m <songtitle.size()-1){
                  if(songtitle.get(m).substring(0, 1).equals( songtitle.get(m+1).substring(0, 1))){
                      m++;
                  }else{

                songstoadd.add(songtitle.get(m));
                adapter.addSection(songtitle.get(m).substring(0, 1), new ArrayAdapter<String>(getApplicationContext(),R.layout.song, songstoadd));

              m++;
                  }

For more info look at

Android: how to use SectionIndexer

Using AlphabetIndexer for fastscrolling ListView

Create easy alphabetical scrolling in ListView?

Community
  • 1
  • 1
user370305
  • 108,599
  • 23
  • 164
  • 151
0

Try changing your while as below and try..

while(m <songtitle.size()-1){
     if(songtitle.get(m).substring(0, 1) == songtitle.get(m+1).substring(0, 1)){
         songstoadd.add(songtitle.get(m));
         m++;
     }else{

         songstoadd.add(songtitle.get(m));

         adapter.addSection(songtitle.get(m).substring(0, 1), new ArrayAdapter<String>(getApplicationContext(),R.layout.song, songstoadd));

         songstoadd.clear();

         m++;
    }
}
Sush
  • 6,839
  • 1
  • 18
  • 26