我的要求是我需要调用API,每次从一个数组列表中传递50个项目。
例如,我有一个150的数组列表,现在我需要从数组列表中获取前50个项并将其传递给API调用,下一次迭代我应该将下50个项传递给API调用,
到目前为止,我已经尝试过了,但并不像预期的那样工作,第一次迭代得到50个项目,API调用在下一个50个项目迭代时发生,但始终显示前50个项目,第二次API调用只与第一个项目列表一起传递。
下面是我的代码:
if (synchedList.size() > 0) {
for (int i = 0; i < synchedList.size(); i += 50) {
List < ContactsEntity > subList = synchedList.subList(i, Math.min(synchedList.size(), i + 50));
Log.d(TAG, "sub list:" + subList.size());
//api call
}
}
有谁能让我知道如何迭代,每次从数组列表中获取范围为50的项目?
如有帮助,不胜感激!
只需记住“页面”,这样你就可以计算出现在所需的子列表。
类似于
class Sender {
private static int PAGE_SIZE = 50;
private int mPage = 0;
private List<Item> mSource;
...
// Sends items to api. Returns true if call was made.
// If there is no more items to send, returns false.
boolean sendNext() {
if (mPage * PAGE_SIZE > mSource.length()) {
// No items to send
return false;
}
// Get sublist
int from = mPage * PAGE_SIZE;
int to = Math.max(from + PAGE_SIZE, mSource.length());
mPage++;
List<Item> sublist = mSource.sublist(from, to);
api.call(sublist);
return true;
}
void sendAll() {
hasMoreItems = true;
while (hasMoreItems) {
hasMoreItems = sendNext();
}
}
}
这是一种简单的方法,但也可以将其拆分为一个单独的方法,并将这些变量作为参数传递。
Integer pageSize = 50;
Integer firstIndex = 0;
Integer endIndex = 0;
if(synchedList.size() > 0 ){
while (endIndex < (synchedList.size())) {
endIndex = firstIndex + pageSize;
if(endIndex > (synchedList.size())) {
endIndex = synchedList.size();
}
api.call(synchedList.subList(firstIntext, endIndex)
firstIndex += pageSize;
}
}
没什么大不了的:
while (items.size()>0) {
List segment = items.subList(0,Math.min(items.size()+1, 50));
//upload segment
items.removeAll(segment);
}