【问题标题】:Passing variable into AsyncHttpResponseHandler callback for Android将变量传递给 Android 的 AsyncHttpResponseHandler 回调
【发布时间】:2012-10-27 00:58:52
【问题描述】:

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

我的代码如下。

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 中,您仍然可以访问代码块内匿名函数之外的变量。如果无法完成,我将不得不自定义我的查询以一次拉回所有数据,然后在客户端解析它,无论如何这是一个更好的解决方案,但我想知道是否访问回调中的项目是可能的。

【问题讨论】:

    标签: java android android-async-http


    【解决方案1】:

    确实,您无法在此范围内访问这些变量,但是您可以尝试通过此代码所在的类的实例来访问它们:

    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());
              }
          });
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以创建一个简单的新类,而不是使用匿名内部类,该类将您希望在 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));
      }
      

      【讨论】:

        猜你喜欢
        • 2011-11-13
        • 1970-01-01
        • 1970-01-01
        • 2019-10-08
        • 1970-01-01
        • 1970-01-01
        • 2017-12-18
        • 2014-10-03
        • 1970-01-01
        相关资源
        最近更新 更多