0

我做一個Android應用程序與改造,我的問題是我需要返回從回調的response.body(),這是我的代碼:改造2異步調用返回響應

public class RoundListProvider { 
    //Load Rounds 
    private static RoundsInterface roundClient = RetroBuilder.createService(RoundsInterface.class); 
    private static RoundList mRoundList; 
    public static RoundList getRoundList(final Context mContext) 
    { 
     Toast.makeText(mContext, "We're in", Toast.LENGTH_LONG).show(); 
     //Fetch info from rounds 
     Call<RoundList> call = roundClient.getRounds(); 
     call.enqueue(new Callback<RoundList>() { 
      @Override 
      public void onResponse(Response<RoundList> response, Retrofit retrofit) { 
       Log.d("BODY", response.body().toString()); 
       Log.d("MESSAGE", response.message()); 
       Toast.makeText(mContext, "Conexión al servidor hecha con exito", Toast.LENGTH_LONG).show(); 
       mRoundList = response.body(); 
      } 

      @Override 
      public void onFailure(Throwable t) { 
       Log.d("BODY", t.getMessage()); 
       Log.d("ERRRO", t.getStackTrace().toString()); 
      } 
     }); 
     return mRoundList; 
    } 
} 

正如你可以想象的那樣,返回的mRoundList總是爲空,因爲從不等待響應完成,有人可以幫我解決這個問題嗎?

+0

幫助你到底是什麼? – Blackbelt

+0

如果您需要整個響應主體,那麼爲什麼不使用OKHttp呢? – jonathanrz

回答

0

您不能混合使用同步方法調用和異步回調 - 一旦您輸入Callback -land,您必須停留在那裏。

調用getRoundList()(在某些ActivityFragment大概)然後做一些事返回值,右邊的代碼?而不是僅僅存儲mRoundListonResponse - 做你想要發生的價值那裏。

0

嗯,問題是我需要在回收站視圖中使用響應數據,所以我這樣做,也許不是最好的,但它的工作原理。在我的供應商我添加了一個新功能:

public static void savedRoundList(RoundList roundList, Activity activity, Context context) 
{ 
    RecyclerView recyclerView = (RecyclerView) activity.findViewById(R.id.rvRounds); 

    recyclerView.setHasFixedSize(true); 

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity); 
    recyclerView.setLayoutManager(linearLayoutManager); 

    List<RoundData> roundData = roundList.getRounds(); 
    RoundAdapter adapter = new RoundAdapter(roundData); 
    Log.d("RESPONSE & ERROR", roundList.getStatus()+ " "+ roundList.getCode()); 

    recyclerView.setAdapter(adapter); 
} 

因此,在回調我只是我們的功能savedRoundList:

savedRoundList(response.body(), mActivity, mContext); 

,瞧,它的工作原理。