Android async-http-client: Add parameters to callbacks?

1.6k views Asked by At

I want to use async-http-client to post data to a server and keep a SQLite on device in sync with this data. So basically i want the whole thing to:

  1. Inert new data to the SQLite
  2. Post the new data to the server using async-http-client
  3. Update the SQLite row in the onSuccess/onFailure Callbacks with additional data

My Question is: How can i get the right row id in the AsyncHttpResponseHandler?

Lets create an easy example (no database connection to keep it simple but same problem).

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

}    

So what is the best way to achieve this? Overriding AsyncHttpResponseHandler to somehow add a parameter to the callback functions?

2

There are 2 answers

0
Lefteris On

Make your variable final, like

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

It's quite simple, you can send rowId.

param.put("_id", rowId);

and, server send it back to the client.

It's good way, because it allows you to make only one AsyncHttpResponseHandler instance. (It's good to instantiate as less as possible)