Frage

I receive data from a server using JSON and I want to order them alphabetically with alphabet indexed section and store them in a ListView. Maybe something that will happen in :

for(int i=0;i<jArray.length();i++){
// here
}

I read that you can order elements like that only using a cursor. In my case would be very inefficient to store the elements from the server in the database and read them again. Waste of time and memory.

So, I am asking you if there could be any solution for my problem : order alphabetically with alphabet indexed section string received from JSON .

EDIT: I want my listview to look like this http://eshyu.wordpress.com/2010/08/15/cursoradapter-with-alphabet-indexed-section-headers/ . I mean with those sections . All tutorials I found said that you need to fetch information with a cursor. My question was if I could't do this wihout a cursor, because it would be a waste of memory to store them in the local database too.

War es hilfreich?

Lösung

You may need to parse the JSON Array :

List<Project> list = new ArrayList<Project>();

for (int i = 0; i < jArray.length(); i++) {
    JSONObject obj = (JSONObject) jArray.get(i);
    project = new Project();
    project.setId( Long.parseLong(obj.get("id").toString()));
    project.setKey(obj.get("key").toString());
    project.setName(obj.get("name").toString());

    list.add(project);
}

You can use the comparator class like this to sort them :

Collections.sort(list), new Comparator<Project>() {
    public int compare(Project p1, Project p2) {
        return p1.getKey().compareToIgnoreCase(p2.getKey());
    }
});

You can also have Project class and implements Comparable:

public class Project implements Comparable<Project> {
   private long id;
   private String key;
   private String name;

   public int compareTo(Project p) {
    if (this.key > p.key)
        return -1;
    else if (this.key < p.key)
        return 1;
    return 0;
   }
}

And then sort the list by Collections.sort(list);

My suggestion is try to sort the data in the Server-side, because the memory of the phone is limited and it may make you application time consuming to show the data, but you do not have memory limitation problem in the Server-side.

Andere Tipps

use a comparator to sort the arraylist as described here . And then use an ArrayAdapter to show the items in Listview

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top