Sorting Android ListView

Posted by aeoth on Stack Overflow See other posts from Stack Overflow or by aeoth
Published on 2010-04-14T07:48:38Z Indexed on 2010/04/14 7:53 UTC
Read the original article Hit count: 1013

Filed under:
|
|

I'm only starting with Android dev, and while the Milestone is a nice device Java is not my natural language and I'm struggling with both the Google docs on Android SDK, Eclipse and Java itself. Anyway...

I'm writing a microblog client for Android to go along with my Windows client (MahTweets). At the moment I've got Tweets coming and going without fail, the problem is with the UI.

The initial call will order items correctly (as in highest to lowest)

  • 3
  • 2
  • 1

When a refresh is made

  • 3
  • 2
  • 1
  • 6
  • 5
  • 4

After the tweets are processed, I'm calling adapter.notifyDataSetChanged(); Initially I thought that getItem() on the Adapter needed to be sorted (and the code below is what I ended up with), but I'm still not having any luck.

public class TweetAdapter extends BaseAdapter
{
private List<IStatusUpdate> elements;
private Context c;
public TweetAdapter(Context c, List<IStatusUpdate> Tweets)
{
    this.elements = Tweets;
    this.c = c;
}
public int getCount() {

    return elements.size();
}
public Object getItem(int position) {
    Collections.sort(elements, new IStatusUpdateComparator());
    return elements.get(position);
}
public long getItemId(int id) {
    return id;
}
public void Remove(int id)
{   
    notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) 
{
    RelativeLayout rowLayout;
    IStatusUpdate t = elements.get(position);
            rowLayout = t.GetParent().GetUI(t, parent, c);
    return rowLayout;
}

class IStatusUpdateComparator implements Comparator
{
    public int compare(Object obj1, Object obj2)
    {
        IStatusUpdate update1 = (IStatusUpdate)obj1;
        IStatusUpdate update2 = (IStatusUpdate)obj2;
        int result = update1.getID().compareTo(update2.getID());

        if (result == -1)
        return 1;
        else if (result == 1)
        return 0;
        return result;
    }
}
}

Is there a better way to go about sorting ListViews in Android, while still being able to use the LayoutInflater? (rowLayout = t.GetParent().GetUI(t, parent, c) expands the UI to the specific view which the microblog implementation can provide)

© Stack Overflow or respective owner

Related posts about android

Related posts about java