【问题标题】:Android async-http-client: Add parameters to callbacks?Android async-http-client:向回调添加参数?
【发布时间】:2013-12-15 08:57:55
【问题描述】:

我想使用async-http-client 将数据发布到服务器并保持设备上的 SQLite 与这些数据同步。所以基本上我想要整件事:

  1. 向 SQLite 惰性化新数据
  2. 使用 async-http-client 将新数据发布到服务器
  3. 使用附加数据更新 onSuccess/onFailure 回调中的 SQLite 行

我的问题是:如何在 AsyncHttpResponseHandler 中获取正确的行 ID?

让我们创建一个简单的示例(没有数据库连接以保持简单但同样的问题)。

private void addPerson(name){

  //using a global client created like this in activity onCreate():
  //AsyncHttpClient client = new AsyncHttpClient();

  //here is a database insert creating a new row, returning the inserted id
  int rowId = <some id returned by the insert>;

  RequestParams param = new RequestParams();
  param.put("name", name);

  client.post("http://www.my.service.url", param, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
      //The response i get contains an additional value, lets say userkey. I want to update the right database row with that information.
      //How to get the right rowId here?
    }
  });

}    

那么实现这一目标的最佳方法是什么?重写 AsyncHttpResponseHandler 以某种方式向回调函数添加参数?

【问题讨论】:

    标签: android asynchronous android-async-http


    【解决方案1】:

    让你的变量最终化,比如

    final int rowId = <some id returned by the insert>;
    

    【讨论】:

      【解决方案2】:

      很简单,发送rowId即可。

      param.put("_id", rowId);

      然后,服务器将其发送回客户端。

      这是个好方法,因为它只允许你制作一个 AsyncHttpResponseHandler 实例。 (尽量少实例化就好)

      【讨论】:

      • 我也将其作为一种方法来实现,但我不确定这是否是好的做法:是吗?并且:如果我无法访问服务器怎么办,那么这可能是个问题。
      • @homtg 如果你没有 aceess,你可以通过改变参数来检查,比如 private void addPerson(rowId, name)
      猜你喜欢
      • 2016-09-07
      • 2012-10-25
      • 2015-12-27
      • 2015-06-05
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2013-01-27
      相关资源
      最近更新 更多