Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

sorting - Android sort ListView alphabetically

So I'm trying to sort a simple ArrayAdapter for ListView. Here's what I've tried:

ListView lv;
String[] months = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
};

ArrayAdapter<String> adapter;
ArrayList<String> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lv = (ListView) findViewById(R.id.listView1);
    lv.setFastScrollEnabled(true);
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, months);
    lv.setAdapter(adapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub

    switch (item.getItemId()) {
        case R.id.sortasc:
            list = new ArrayList<String>(Arrays.asList(months));
            Collections.sort(list);
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
            adapter.clear();
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, list);
            adapter.notifyDataSetChanged();
            return true;
        case R.id.sortdesc:

            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

But I'm getting UnsupportedOperationException, what's wrong with this? I really need help. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You didn't called setAdapter(adapter), after sorting your items.

Use like below

adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();

instead of

adapter.clear(); // Useless 
adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...