本文介绍了如何从Retrofit onResponse()更新Activity / Fragment UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的下一个Android项目中使用Retrofit 2.1.0。我想使用设计模式,因此为每个REST调用创建单独的类,即
I want to use Retrofit 2.1.0 for my next Android project. I would like to use Design Pattern and therefore create separate classes for every REST call i.e
IBalanceService.java
IBalanceService.java
public Interface IBalanceService{
@GET("users/{username}")
void getUser(@Path("username") String username, Callback<User> cb);
}
BalanceRestClient.java
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
BalanceActivity.java
public BalanceActivity extends Activity{
// BalanceRestClient will update some UI elements
}
如何从onResponse()更新Activity / fragment中的UI?
How can I update UI in my Activity/fragment from onResponse()?
推荐答案
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
}
});
}
}
- 创建单例类。它只会初始化一次请求。
- 创建一个自定义回调函数,它将返回您对UI的响应。
- 调用BalanceRestClient.getInstance.getRequest( params ..)你想要使用它。
这篇关于如何从Retrofit onResponse()更新Activity / Fragment UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!