String[] temp = new String[adapter.getCount()];
for(int i = 0; i < adapter.getCount(); i++)
temp[i] = adapter.getItem(i).toString();
List<String> list = Arrays.asList(temp);
Collections.sort(list);
adapter.clear();
comment = new Comment();
for(int i = 0; i < temp.length; i++)
{
comment.setComment(temp[i]);
System.out.println("comment is: " + comment.getComment());
adapter.insert(comment, i);
System.out.println("adapter is: " + adapter.getItem(i));
}
for(int i = 0; i < adapter.getCount(); i++)
System.out.println(adapter.getItem(i));
The code above performs the sorting of the ArrayAdapter which is typed ; a helper class as I am using SQLiteHelper and SQL database.
Ok so I verify, after clearing all data within the ArrayAdapter, that the data is added within a lexicographic sorted order.
However, by the time I reach the final for loop to verify this, the ArrayAdapter has replicated the last item in the list at every index. This is weird and makes no sense to me. Of course this is also reflected on the screen.
Can you provide assistance to understand what is going please?
You are using the same instance of ‘Comment’ throughout the ArrayAdapter. Hence, all positions of the ArrayAdapter have the exact same ‘comment’ object reference. This single instance has been set to the final string from the original list and so all ListView items will look the same. The solution is to move the instantiation of ‘comment’ into the for loop to create a unique ‘comment’ instance for each adapter position. I’ve also slightly optimized your code.
EDIT
Also, since you’re inserting/adding one at a time, you might want to delay notifyDataSetChanged from executing until after all modifications are completed. This will prevent the ListView from refreshing on every modification. I’ve included it in the code above.