java - Android - 通过改造调用 API 时显示加载栏
问题描述
在我的应用程序中,我使用改造 2 从 API 检索数据。我对此没有任何问题。问题是我想在执行时显示一个加载栏。代码是这样的
Call<MainInvestorProducts> call = apiInterface.getUseraccounts("Bearer "+bearerToken);
mkLoader.setVisibility(View.VISIBLE);
call.enqueue(new Callback<MainInvestorProducts>() {
@Override
public void onResponse(Call<MainInvestorProducts> call, Response<MainInvestorProducts> response) {
// If success response set the textViews
if (response.code() == 200) {
retrievedData = response.body();
//else display error message
}else if (response.code() == 401) {
Toasty.error(getApplicationContext(), getString(R.string.expired_token),Toasty.LENGTH_LONG).show();
finish();
}
}
@Override
public void onFailure(Call<MainInvestorProducts> call, Throwable t) {
}
});
mkLoader.setVisibility(View.GONE);
问题是 mkloader 永远不会出现。
我的 APIClient 代码
public class APIClient {
public static Retrofit retrofit = null;
public static Retrofit getClient(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("https://api-test01.moneyboxapp.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
这是接口的一个例子
@Headers({
"AppId: 3a97b932a9d449c981b595",
"Content-Type: application/json",
"appVersion: 5.10.0",
"apiVersion: 3.0.0"
})
@POST("/users/login")
Call<MainUserLogin> logInUser(@Body LoginBody loginBody);
解决方案
mkLoader.setVisibility(View.VISIBLE);
Call<MainInvestorProducts> call = apiInterface.getUseraccounts("Bearer "+bearerToken);
call.enqueue(new Callback<MainInvestorProducts>() {
@Override
public void onResponse(Call<MainInvestorProducts> call, Response<MainInvestorProducts> response) {
// If success response set the textViews
if (response.code() == 200) {
retrievedData = response.body();
//else display error message
}else if (response.code() == 401) {
Toasty.error(getApplicationContext(), getString(R.string.expired_token),Toasty.LENGTH_LONG).show();
finish();
}
}
@Override
public void onFailure(Call<MainInvestorProducts> call, Throwable t) {
mkLoader.setVisibility(View.GONE);
}
});
您只需要在调用 API 之前使加载程序对 VISIBLE 可见,如果 api 成功或失败,您将可见性设置为 GONE
推荐阅读
- git - 创建拉取请求后,Jenkins 管道脚本将持续运行
- cortana - cortana 是用什么语言编写的?
- xml - 如何将xml加载到draw.io图中?
- php - POST请求的PHP cURL CURLAUTH_NEGOTIATE问题
- google-apps-script - 您可以在 Google 表格中对列(水平)进行排序吗?
- c# - 如何在实体框架中使用两个模型类进行连接
- google-apps-script - 使用中间有空格的getNotes?
- c - SIG_IGN 关于 SIGFPE、SIGILL、SIGSEGV 的未定义行为规范是否多余?
- mysql - 计算按国家分组的一列中的比率
- c++ - 用大 O 表示法表示的 mandelbrot 集的时间复杂度