我想在我的下一个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()更新Activity / fragment中的UI?
附加信息:
改进2.1.0
min SDK:19
目标SDK:23
用OkHttp和gson
答案 0 :(得分:2)
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 :(得分:0)
在这样的界面上创建一个界面:
public interface BalanceListener {
void onUserAvailable(User user);
}
在 BalanceRestClient 中有一个实例。并在 onResponse :
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
listener.onUserAvailable(user);
}
让您的活动实施 BalanceListner :
public class BalanceActivity extends Activity implements BalanceListener {
......
@Override
public void onUserAvailable(User user) {
// update user views here
}
}