Java pagination

I wrote swap logic:

My requirement: total number of elements to display: 100 per page, if I click on next, it should display the next 100 entries, if I click on the previous 100 entries.

Initial variability values:

  • showFrom: 1,
  • showTo: 100
  • Maximum Elements: Depends on the size of the data.
  • PAGESIZE :. 100

the code:

if(paging.getAction().equalsIgnoreCase("Next")){ paging.setTotalRec(availableList.size()); showFrom = (showTo + 1); showTo = showFrom + 100- 1; if(showTo >= paging.getTotalRec()) showTo = paging.getTotalRec(); paging.setShowFrom(showFrom); paging.setShowTo(showTo); } else if(paging.getAction().equalsIgnoreCase("Previous")){ showTo = showFrom - 1; showFrom = (showFrom - 100); paging.setShowTo(showTo); paging.setShowFrom(showFrom); paging.setTotalRec(availableList.size()); } 

Here I can delete and add items to existing data. The new code works fine if I add and remove multiple elements. But if I delete or add 100 elements at a time, then the counts are not displayed correctly; the code works fine if I add and remove several elements.

+1
source share
2 answers

Some improvements:

  • replace the value "magic" 100 with final int PAGE_SIZE = 100;
  • multiply the redundant code.
  paging.setShowTo(showTo); paging.setShowFrom(showFrom); paging.setTotalRec(availableList.size()); 

to make your logic clearer outside if / else

  • Make sure previous> = 0 and next <= number of entries

Edit:

 final int PAGE_SIZE = 100; int numberOfPages = -1; int currentPage = -1; public void initializeVariables(){ paging.setTotalRec(availableList.size()); showFrom = 1; showTo = PAGE_SIZE; //keep track of how many pages there should be numberOfPages = paging.getTotalRec()/PAGE_SIZE; currentPage = 1; } public void handlePagingAction(){ if(paging.getAction().equalsIgnoreCase("Next")){ if(currentPage < numberOfPages){ ++currentPage; } }else if(paging.getAction().equalsIgnoreCase("Previous")){ if(currentPage > 1){ --currentPage; } } showFrom = (currentPage - 1) * PAGE_SIZE + 1; if(showFrom < 0){ showFrom = 0 } showTo = currentPage * PAGE_SIZE; if(showTo >= paging.getTotalRec()){ showTo = paging.getTotalRec(); } paging.setShowTo(showTo); paging.setShowFrom(showFrom); } 
+1
source

Some notes:

  • In the line showTo = showFrom + 100- 1; why minus 1?
  • If showTo is equal to paging.getTotalRec (), the next time you click Next, showFrom will overload paging.getTotalRec ()
  • In the previous part, there are no tests to prevent a transition below 0

Hope this helps ...

+1
source

Source: https://habr.com/ru/post/899608/


All Articles