Search code examples
sortinggwtcelltable

Gwt CellTable Sorting page by page only


GWT CellTable column sorting page by page only, for each page i have to click the column header for sorting. How to sort whole data on single header click. This is my code,

   dataProvider = new ListDataProvider<List<NamePair>>();
   dataProvider.addDataDisplay(dgrid);
   List<List<NamePair>> list = dataProvider.getList();

   for (List<NamePair> contact : test) {
      dataProvider.setList(test);
      list.add(contact);
   }


   ListHandler<List<NamePair>> columnSortHandler = new ListHandler<List<NamePair>>(dataProvider.getList());
   System.out.println("Column count->"+dgrid.getColumnCount());

   for(int j=0 ; j<dgrid.getColumnCount();j++){             
        final int val = j;
        columnSortHandler.setComparator(dgrid.getColumn(val), new Comparator<List<NamePair>>() {

        public int compare(List<NamePair> o1, List<NamePair> o2) {
          if (o1 == o2) {
            return 0;
         }

         // Compare the column.
         if (o1 != null) {
            int index = val;
            return (o2 != null) ? o1.get(index-2).compareTo(o2.get(index-2)) : 1;
         }
         return -1;
        }
    });
}

dgrid.addColumnSortHandler(columnSortHandler);

Solution

  • I suggest you override ListHandler , override and call super.onColumnSort(ColumnSortEvent) to debug the onColumnSort(ColumnSortEvent) method, you'll understand what is happening very fast.

    The source code of the method is pretty direct

    public void onColumnSort(ColumnSortEvent event) {
      // Get the sorted column.
      Column<?, ?> column = event.getColumn();
      if (column == null) {
        return;
      }
    
      // Get the comparator.
      final Comparator<T> comparator = comparators.get(column);
      if (comparator == null) {
        return;
      }
    
      // Sort using the comparator.
      if (event.isSortAscending()) {
        Collections.sort(list, comparator);
      } else {
        Collections.sort(list, new Comparator<T>() {
          public int compare(T o1, T o2) {
            return -comparator.compare(o1, o2);
          }
        });
      }
    }