コールバックインターフェイスを使用して、呼び出し元にデータを戻すことができます。以下の例を考えてみましょう:
public interface CardsResponse {
onResponseReceived(JSONObject response);
}
次に、あなたのgetCards
意志は次のようになります。
public static void getCards(Context context, CardsResponse cardsResponse)
{
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("x-access-token", Preferences.getToken(context));
client.get("http://api.app.com/users/" + Preferences.getID(context), null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
Log.d("debugIID", "Cards success : " + statusCode);
String json = new String(bytes);
try {
jsonObj = new JSONObject(json);
cardsResponse.onResponseReceived(jsonResponse); // This line will return to your caller
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("debug", "Cards JSONObject : " + jsonObj);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
Log.d("debug", "Cards failure : " + statusCode);
}
});
}
そして最後に、発信者:
final JSONObject json = Cards.getCards(getApplicationContext(), new CardsResponse() {
@Override
public void onResponseReceived(JSONObject response) {
// Do stuff here
Log.d("DebudIID", "Cards JSON : " + json);
}
});
非同期の全体のポイントは、あなたが行うことができないということですあなたの関数は成功の前に戻ります。 – SLaks