Reputation: 107
In my app, my goal is for the user to upload an image from their gallery, and save it in a database. Each image will have a name and that name and image will be displayed in a listview. The listviews will be sorted kind of like contacts in a phone. What they are exactly are maps of properties, such as different hotels or resorts, or even schools, for the purpose of delivering. I have everything working the way that I want, but for some reason I'm having trouble getting them into alphabetical order. I've tried other examples and snippets, but with no luck. The code I have for it is as follows:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.display_hotels);
db = new DatabaseHandler(this);
lv = (ListView) findViewById(R.id.list1);
pic = (ImageView) findViewById(R.id.pic);
fname = (EditText) findViewById(R.id.txt1);
final ArrayList<Hotel> hotels = new ArrayList<>(db.getAllHotels());
data = new dataAdapter(this, hotels);
Collections.sort(hotels, new Comparator<Hotel>()
{
public int compare(Hotel a1, Hotel a2)
{
return (a1.toString()).compareTo(a2.toString());
}
});
lv.setAdapter(data);
}
Before I put the code in for the comparisons:
Collections.sort(hotels, new Comparator<Hotel>()
{
public int compare(Hotel a1, Hotel a2)
{
return (a1.toString()).compareTo(a2.toString());
}
});
It would simply display the images in the order that they were saved. But with this chunk of code, it seems that something is wrong. I tried saving 3 different images of properties: Westgate Resort, Grand Country Inn, and College of the Ozarks, in that order. And for some reason, Westgate was shown first, College of the Ozarks second, and Grand Country Inn third. If I add the same image and name it Grand Country Inn as well, Westgate Resort will fall to the bottom of the list. Which seems correct, but upon adding another image, Westgate will go back to the top. Any help would be greatly appreciated! Thank you for your time.
Upvotes: 2
Views: 898
Reputation: 107
I managed to figure it out. Instead of using the Collections.sort() method, I just used sort() on my adapter.
data = new dataAdapter(this, hotels);
data.sort(new Comparator<Hotel>()
{
@Override
public int compare(Hotel arg0, Hotel arg1)
{
return arg0.getFName().compareTo(arg1.getFName());
}
});
data.notifyDataSetChanged();
lv.setAdapter(data);
I'm not sure if it's bad practice or not, but for what I want, it works perfect.
Upvotes: 1
Reputation: 849
Please do consider adding
data.notifyDataSetChanged()
each time you add an element into the list.
Another thing that you can do is to lower case each element before adding them into the list. Or try this code
Collections.sort(hotels, new Comparator<Hotel>(){
public int compare(Hotel a1, Hotel a2)
{
return (a1.toString().toLowerCase()).compareTo(a2.toString().toLowerCase());
}
});
Upvotes: 0