小编典典

如何从Retrofit onResponse()更新活动/片段UI?

java

我要在我的下一个Android项目中使用Retrofit 2.1.0。我想使用设计模式,因此为每个REST调用创建单独的类,即

IBalanceService.java

public Interface IBalanceService{
  @GET("users/{username}")
  void getUser(@Path("username") String username, Callback<User> cb);
}

BalanceRestClient.java

public class BalanceRestClient{

  String username = "Makarov";

  Retrofit retrofit = new Retrofit.Builder()
                               .baseUrl("http://hovermind.com")
                               .addConverterFactory(GsonConverterFactory.create())
                               .addCallAdapterFactory(rxAdapter)
                               .build();

  IBalanceService bs = retrofit.create(IBalanceService.class);


  Call<User> call = apiService.getUser(username);
  call.enqueue(new Callback<User>() {

      @Override
      public void onResponse(Call<User> call, Response<User> response) {

          User user = response.body();

          // update Activity/Fragment from here

      }

      @Override
      public void onFailure(Call<User> call, Throwable t) {
        // Log error here since request failed
      }

   });
}

BalanceActivity.java

public BalanceActivity extends Activity{

   // BalanceRestClient will update some UI elements 
}

如何通过onResponse()更新活动/片段中的UI?

附加信息:
最小SDK:19个
目标SDK:23个
使用OkHttp和gson改造的2.1.0


阅读 514

收藏
2020-11-26

共1个答案

小编典典

 public class BalanceRestClient {

            private static BalanceRestClient instance;
            private IBalanceService request;

            private BalanceRestClient() {
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://hovermind.com")
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(rxAdapter)
                        .build();

                request = retrofit.create(IBalanceService.class);
            }

            public static synchronized BalanceRestClient getInstance() {
                if (instance == null)
                    instance = new BalanceRestClient();

                return instance;
            }

            public void getRequest(String userName, YourCustomeCallback callback) {

                Call<User> call = apiService.getUser(username);
                call.enqueue(new Callback<User>() {

                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {

                        User user = response.body();

                        callback.onResponse(user);

                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {
                        // Log error here since request failed
                    }

                });
            }
        }
  1. 创建一个单例类。它只初始化一次请求。
  2. 创建一个自定义回调,它将使您的响应返回给UI。
  3. 在要使用它的地方调用BalanceRestClient.getInstance.getRequest(params ..)。
2020-11-26