首页 > 解决方案 > 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);

标签: javaandroidretrofit

解决方案


    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


推荐阅读