Aniket Bhattacharyea Aniket Bhattacharyea - 1 year ago 55
Android Question

Collections.sort is not sorting data

I have a custom class called

Song
like this-

public class Song implements Parcelable {
private String mTitle;
private String mArtist;
private long mID;
private long albumID;

public Song(long id,String title, String artist,long albumId)
{
this.mID=id;
this.mTitle=title;
this.mArtist=artist;
this.albumID=albumId;
}

public long getAlbumID() {
return albumID;
}

public void setAlbumID(long albumID) {
this.albumID = albumID;
}

public long getID()
{
return mID;
}

public String getArtist() {
return mArtist;
}

public String getTitle() {
return mTitle;
}

public void setID(long mID) {
this.mID = mID;
}

public void setTitle(String mTitle) {
this.mTitle=mTitle;
}

public void setArtist(String mArtist) {
this.mArtist = mArtist;
}


@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mTitle);
parcel.writeString(mArtist);
parcel.writeLong(mID);
parcel.writeLong(albumID);
}

public static final Parcelable.Creator CREATOR=new Parcelable.Creator()
{
public Song createFromParcel(Parcel in)
{
return new Song(in);
}

public Song[] newArray(int size)
{
return new Song[size];
}
};
public Song(Parcel in)
{
mTitle=in.readString();
mArtist=in.readString();
mID=in.readLong();
albumID=in.readLong();

}


}


and a
ArrayList<Song>
.

I want to sort the data alphabetically. I'm using-

Collections.sort(songList, new Comparator<Song>() {
@Override
public int compare(Song a, Song b) {
return (a.getTitle().compareToIgnoreCase(b.getTitle()));
}
});


However, my data is still not sorted. The list starts with a song starting with "h", then one with "o" and then one with "s".

Answer Source

Found out the problem. I was fetching the songList in a Thread and sorting it outside the Thread. So, it was sorting the data before the Thread finished fetching the data. Moved the sort part inside the Thread and it worked.