我有一个带有分页功能的jqgrid。用户可以自行输入数据以在页面之间输入数据。
如果用户在第 199 行输入的页面超过可用页面,我会收到错误,如上例所示。如何解决这个问题?
if(noOfRows != null && !recipeList.isEmpty())
if ((noOfRows * pageNo) < recipeList.size()) {
recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
(noOfRows * pageNo));
} else {
recipeList = recipeList.subList((noOfRows * (pageNo - 1)),
recipeList.size()); //line 199: giving error
}
for (Recipe recp : recipeList) {
..............
..............
我试图更改代码的 else 部分,其中 199 行:
int totalCustomPagesNums=noOfRows * (pageNo - 1);
int firstIndex=totalCustomPagesNums < recipeIdList.size()?totalCustomPagesNums:1;
recipeList = recipeList.subList(firstIndex,
recipeList.size());
我会将其简化为:
- 计算出下限,该下限必须至少为 0,最多为
recipeList.size()
- 计算出独占上限,该上限必须至少为 0,最多为
recipeList.size()
- 获取子列表
所以:
int start = Math.min(Math.max(noOfRows * (pageNo - 1), 0), recipeList.size());
int end = Math.min(Math.max(noOfRows * pageNo, start), recipeList.size());
recipeList = recipeList.subList(start, end);
现在您确定0 <= start <= end <= recipeList.size()
,因此即使用户指定了奇怪的行数或页码,也会没问题。
您正在尝试创建一个从索引 100 开始到索引 72 结束的子列表。由于列表的开头在结尾后面,因此您将获得IllegalArgumentException。
如果(noOfRows*pageNo < recipeList.size())
,请添加另一个检查。
我会在代码的开头添加两个额外的块。
if (pageNo < 1) {
pageNo = 1;
}
if ((pageNo - 1) * noOfRows >= recipeList.size()) {
pageNo = 1 + ( recipeList.size() - 1 ) / noOfRows;
}
如果页码太低,第一个块会修复问题。 如果页码太高,第二个块会修复问题。
第二个块开头的检查是确保要显示的第一个配方的索引((pageNo - 1) * noOfRows
)在 recipeList
的范围内。 里面的赋值是将pageNo
设置为最大值,这是真的。