Avinash Kumar Pankaj
Avinash Kumar Pankaj

Reputation: 1720

how to sort data alphabetically in spinner

i am new in android field and i want to sort my spinner data alphabetically. please help

note:- i am receiving data from web services.

my code is:-

        <Spinner
            android:id="@+id/spinnerAtlasContactSignup"
            android:layout_width="200dip"
            android:layout_height="46dp"
            android:layout_below="@+id/editCompanySignup"
            android:layout_marginBottom="60dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/slect_box1x"
            android:ems="10"
            android:padding="10dp"
            android:prompt="@string/atlas_contact" />

 private void initializeSpinner(ArrayList<AtlasContact> atlastContacts) {

    ArrayAdapter<AtlasContact> adapter = new ArrayAdapter<AtlasContact>(this,android.R.layout.simple_spinner_item, atlastContacts);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinnerAtlasContact.setAdapter(adapter); 

here AtlasContact is a class which accepts the data coming from web services.

Upvotes: 6

Views: 8267

Answers (4)

Priya
Priya

Reputation: 1803

Try Collections.sort(atlastContacts);

Upvotes: 1

Ricky Khatri
Ricky Khatri

Reputation: 960

Have you checked docs? There is sort method in ArrayAdapter.

You just need to implement your own Comparator. I guess it's just:

int compare(String s1, String s2) { return s1.compareTo(s2); }

Upvotes: 0

ashokgelal
ashokgelal

Reputation: 81548

You just need to sort your source:

Collections.sort(atlastContacts, new Comparator<AtlasContact>(){
  public int compare(AtlasContact a1, AtlasContact a2) {
    return a1.getName().compareToIgnoreCase(a2.getName());
  }
});

Upvotes: 6

Sam-In-TechValens
Sam-In-TechValens

Reputation: 2519

If you are fetching the values from the SQLite DB then their works the query to sort the values alphabetically and put them sorted in an ARRAY.

or Try to add data to the ArrayList and just use the Collections class to sort for you::

Collections.sort(SourceArray);

Also,

Comparable interface and implement the method compareTo()

Upvotes: 7

Related Questions