Search code examples
androidsortingarraylistandroid-listview

How to sort a jsonarray data by Date & Time and put in list view adapter


here my jsonArray data like:

  [{"LeadId":4,
   "CoreLeadId":0,
   "CompanyId":7,
   "AccountNo":"5675",
   "ScheduleOn":"2015-05-11T00:00:00"},
  {"LeadId":7,
   "CoreLeadId":2,
   "CompanyId":8,
   "AccountNo":"sample string 4",
   "ScheduleOn":"2015-12-01T15:04:23.217"}]   

i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.

   JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
   listItemService = new Gson().fromJson(jsonArray.toString(),
            new TypeToken<List<AppointmentInfoDto>>() {
            }.getType());
    mAdapter = new AdapterAppointment(getActivity(), listItemService);
    listView.setAdapter(mAdapter);

Solution

  • You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.

    Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
    
        @Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
            // Compare l.ScheduleOn and r.ScheduleOn
        }
    
    }