sivan esan
sivan esan

Reputation: 153

Spinner data sorting in Android

I have spinner with array list thats work fine, but i want to sort out the datas from a to z (example: apple,ball,cat,dog...)order. I submit my code below

    ArrayList<String> SourceArray = new ArrayList<String>();
    Spinner Sourcespinner;// = new Spinner(this);
    Sourcespinner = (Spinner)findViewById(R.id.Spinner1);
    ArrayAdapter<String> SourceArrayAdapter = new ArrayAdapter<String>(this,
     android.R.layout.simple_spinner_item,SourceArray);
    SourceArrayAdapter.add("Chennai");
    SourceArrayAdapter.add("Mumbai");
    SourceArrayAdapter.add("Kolkatta");
    SourceArrayAdapter.add("Delhi");
    Sourcespinner.setAdapter(SourceArrayAdapter);`

I don't know how to do sorting for this

Upvotes: 1

Views: 6165

Answers (2)

Tim
Tim

Reputation: 6712

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

Collections.sort(SourceArray);

If you need to add your own objects they need to implement the Comparable interface and implement the method compareTo(). When changing the ArrayList's data make sure to notify the adapter that new data might have been added by using this code:

SourceArrayAdapter.notifyDataSetChanged();

Upvotes: 0

Mert
Mert

Reputation: 6572

you can use this to sort your data

Collections.sort(SourceArray);

Upvotes: 1

Related Questions