2016-05-11 1 views
0

を戻します:待機するonSuccessは私のCards.classにそのようないくつかのJSONファイルを取得するために、私は機能を持つクラスを持っているJSON

final JSONObject json = Cards.getCards(getApplicationContext()); 
Log.d("DebudIID", "Cards JSON : " + json); 

問題は、jsonオブジェクトがMainActivityでnullであることです。 getCards関数では、jsonはonSuccessでは正常です。

関数は、onSuccessを待つ前に戻ります。

どうすればいいですか?

ありがとうございます。

+0

非同期の全体のポイントは、あなたが行うことができないということですあなたの関数は成功の前に戻ります。 – SLaks

答えて

0

コールバックインターフェイスを使用して、呼び出し元にデータを戻すことができます。以下の例を考えてみましょう:

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); 
      } 
     }); 
+0

ありがとう!それはうまくいっている! –

関連する問題