如何在Java中使用游标迭代简单回调?
这是我的问题的一个简单例子。假设我有一个返回以下内容的API:如何在Java中使用游标迭代简单回调?,java,android,Java,Android,这是我的问题的一个简单例子。假设我有一个返回以下内容的API: { cursor: 5, items: [ { id: 0, value: "abc" }, { id: 1, value: "abc" }, { id: 2, value: "abc" }, { id: 3, value: "abc" }, { id: 4, value: "abc" } ] } 然后在获取最后一项后: {
{
cursor: 5,
items: [
{ id: 0, value: "abc" },
{ id: 1, value: "abc" },
{ id: 2, value: "abc" },
{ id: 3, value: "abc" },
{ id: 4, value: "abc" }
]
}
然后在获取最后一项后:
{
cursor: -1,
items: [
{ id: 20, value: "abc" },
{ id: 21, value: "abc" },
{ id: 22, value: "abc" }
]
}
现在我有了一个Java函数(为我编写的,我不能修改它),它接受一个游标和一个回调对象:
requestItems(5, new Callback() {
@Override
public void onResponse ( ItemResponse response )
{
response.getCursor(); // --> 10
response.getItems(); // --> ArrayList<Item>
}
});
我尝试使用递归,但这引发了编译时错误:
final Callback checkForMoreItems = new Callback() {
@Override
public void onResponse ( Response response )
{
if (reponse.getCursor() > -1)
requestItems(response.getCursor(), checkForMoreItems); // <-- Error line
else
continueExecution();
}
}
requestItems(0, checkForMoreItems);
您应该如何处理这样的递归回调?尝试使用
this
而不是checkForMoreItems
:
requestItems(response.getCursor(), this);
这应该可以解决变量未初始化的问题,因为从技术上讲,它是您创建的匿名类对象的属性。另一个解决方案可能是将整个代码分解到它自己的类文件中,在这种情况下,您还需要使用this
error: variable checkForMoreItems might not have been initialized
requestItems(response.getCursor(), this);