2012-10-27 61 views
3

我正在使用AsyncHttpResponseHandler从RESTful服务中收集数据。我遇到的问题是,我无法访问onSuccess回调中需要的变量。将变量传递给Android的AsyncHttpResponseHandler回调函数

我的代码如下。

for (int i=0; i<=count; i++) { 
     requestItemsByCategory(context, categories.get(i), 10, new AsyncHttpResponseHandler() { 
      @Override 
      public void onSuccess(String response) { 
       loadItemsFromJsonString(context, response, categories.get(i)); 
      } 
     }); 
    } 

上下文和类别在onSuccess中显然不可用。我可以创建这些全局变量,但问题是这会导致一个循环,所以onSuccess将被调用几次,但不能保证哪一个会首先返回。

我对Java很新。在Objetive-C中,您仍然可以访问代码块内匿名函数之外的变量。如果它不能完成,我将不得不自定义我的查询以立即撤回所有数据,然后解析它在客户端,无论如何,这是一个更好的解决方案,但我想知道是否访问回调内的项目是可能的。

回答

2

事实上,你不能在此范围内使用这些变量,但是你可以尝试通过类此代码的实例来访问它们:

class YourCoolActivity extends Activity { 

    // + getter/setter 
    private int index; 

    // The rest of the class 

private void yourCoolMethod(){ 
    for (int i=0; i<=count; i++) { 
     this.setIndex(categories.get(i)); 
     requestItemsByCategory(this.getContext(), categories.get(i), 10, new AsyncHttpResponseHandler() { 
      @Override 
      public void onSuccess(String response) { 
       loadItemsFromJsonString(YourCoolActivity.this.getContext(), response, YourCoolActivity.this.getIndex()); 
      } 
     }); 
    } 
    } 
} 
0

而不是使用匿名内部类,你可以创建一个简单的新这个类将构造函数的参数作为参数传递给onSuccess方法。

class MyResponseHandler extends AsyncHttpResponseHandler() { 
    private Context context; 
    private Category category; 
    public MyResponseHandler(Context context, Category category) { 
     this.context = context; 
     this.category = category; 
    } 
    @Override 
    public void onSuccess(String response) { 
     loadItemsFromJsonString(context, response, category); 
    } 
} 

然后你的代码变得

for (int i=0; i<=count; i++) { 
    requestItemsByCategory(context, categories.get(i), 10, new MyResponseHandler(context, categories.get(i)); 
}