android – Initializing retrofit class in another class-ThrowExceptions

Exception or error:

I am working on a retrofit application and I am following a tutorial, but in the tutorial he always creates the following in every class:

       Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://jsonplaceholder.typicode.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Now I have created a retro fit class called APIClient, which has the above in it, plus some security. Here is my API client:

public class APIClient {
    private static OkHttpClient.Builder httpClient;

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl("http://10.0.2.2:8080")
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final Token token) {

        if(httpClient == null){
            System.out.println("client null");
            httpClient = new OkHttpClient.Builder();
            if (!token.getToken().contains("null")) {
                System.out.println("Token not null " + token.getToken());
                httpClient.addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                .header("Accept", "application/json")
                                .header("Authorization", token.getToken())
                                .method(original.method(), original.body());

                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }
                });
            }
            httpClient.connectTimeout(50, TimeUnit.SECONDS);
            httpClient.addInterceptor(addLogging());
        }

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);
    }



    private static HttpLoggingInterceptor addLogging(){

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        return logging;
    }

}

now in the tutorial I am following he does the following:

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);

    Call<List<Post>> call = jsonPlaceHolderApi.getPosts();

Is there any way I can eliminate the whole Retrofit retrofit = new Retrofit.Builder() with my class but still use the retrofit.create part?

How to solve:
public class APIClient {

    private static final String BASE_URL = "http://10.0.2.2:8080/";

    private static OkHttpClient.Builder httpClient;
    private Retrofit retrofit;




    private APIClient() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }


    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final MediaSession.Token token) {

        if (httpClient == null) {
            System.out.println("client null");
            httpClient = new OkHttpClient.Builder();
            if (!token.getToken().contains("null")) {
                System.out.println("Token not null " + token.getToken());
                httpClient.addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        Request.Builder requestBuilder = original.newBuilder()
                                .header("Accept", "application/json")
                                .header("Authorization", token.getToken())
                                .method(original.method(), original.body());

                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }
                });
            }
            httpClient.connectTimeout(50, TimeUnit.SECONDS);
            httpClient.addInterceptor(addLogging());
        }

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);
    }


    private static HttpLoggingInterceptor addLogging() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        return logging;
    }


}

Call<List<Post>> call = APIClient.createService(JsonPlaceHolderApi.class).getPosts();

Leave a Reply

Your email address will not be published. Required fields are marked *