Android async-http-client:为回调添加参数?

时间:2013-12-15 08:57:55

标签: android asynchronous android-async-http

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

  1. 向SQLite发布新数据
  2. 使用async-http-client
  3. 将新数据发布到服务器
  4. 使用其他数据更新onSuccess / onFailure回调中的SQLite行
  5. 我的问题是:如何在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以某种方式向回调函数添加参数?

2 个答案:

答案 0 :(得分:0)

让你的变量最终,比如

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

答案 1 :(得分:0)

这很简单,你可以发送rowId。

param.put(“_ id”,rowId);

并且,服务器将其发送回客户端。

这是好方法,因为它允许你只做一个 AsyncHttpResponseHandler实例。 (最好尽可能少地实例化)