Android:dynamically pass model class to retrofit callback

后端 未结 10 1722
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 04:34

In retrofit to map json response to pojo usually we do this

@POST
Call getDataFromServer(@Url String url, @Body HashMap ha         


        
相关标签:
10条回答
  • 2020-12-05 05:28

    You need to use generics. That way, you can pass the desired type into the call.

    @POST
    Call<T> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap, Class<T> requestClass);
    
    ApiCalls api = retrofit.create(ApiCalls.class);
        Call<T> call = api.getDataFromServer(StringConstants.URL,hashMap);
        call.enqueue(new Callback<T>() {
             //Response and failure callbacks
        }
    

    By the way, I'm no retrofit expert (I use my own stuff mostly), but I think you are using it wrong.

    0 讨论(0)
  • 2020-12-05 05:30

    Use standard generics, with a little bit of hacking around

    Define your interface like this

    public interface ApiCalls<T> {
        @POST
        Call<T> getResult getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);
    }
    

    and call for creating api client use a helper method

    class HelperMethods {
        @SuppressWarnings("unchecked")
        private static <T> ApiCalls<T> getClient() {
            return retrofit.create((Class<ApiCalls<T>>)(Class<?>)ApiCalls.class);
        }
    }
    
    ApiCalls<User> api = HelperMethods.getClient();
    

    But despite of the fact how many times it has been said here, I am gonna say it again... Don't do this .. You are giving up the whole type safety and contract validation that Retrofit is offering .. That is actually the most exciting thing about it..

    0 讨论(0)
  • 2020-12-05 05:32

    First Create Interface:

    public interface
    ItemAPI {
    
        @GET("setup.php")
        Call<SetupDetails> getSetup(@Query("site_id") int id,@Query("ino") String ii);
    
        @GET("setup.php")
        void setMy(@Query("site_id") int id, Callback<List<SetupDetails>> sd);
        }
    

    Now create class:

    public class Apiclient {
    
        private static final String BASE_URL ="http://www.YOURURL.COM/";
        private static Retrofit retrofit = null;
    
        public static Retrofit getClient() {
    
            OkHttpClient.Builder httpClient2 = new OkHttpClient.Builder();
            httpClient2.addNetworkInterceptor(new Interceptor() {
    
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder = chain.request().newBuilder();
                    builder.addHeader("site_id","1");
                    return chain.proceed(builder.build());
                }
            });
            OkHttpClient client = httpClient2.build();
    
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    

    Now in any activity just use:

    ItemAPI itemAPI = Apiclient.getClient().create(ItemAPI.class);
         Call<AllProducts> call=itemAPI.getSetup(1,count);
         call.enqueue(new Callback<AllProducts>() {
                @Override
                public void onResponse(Call<AllProducts> call, Response<AllProducts> response) {
                    try {
                        if (response.body().getItem().size()>0){
    
                        }
    
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
    
                @Override
                public void onFailedAfterRetry(Throwable t) {
    
                }
            });
    
    0 讨论(0)
  • 2020-12-05 05:33

    You can build main pojo like this

    public class BaseResponse<T>
    {
        @SerializedName("Ack")
        @Expose
        private String ack;
    
        @SerializedName("Message")
        @Expose
        private String message;
    
        @SerializedName("Data")
        @Expose
        private T data;
    
        /**
         *
         * @return
         * The ack
         */
        public String getAck() {
            return ack;
        }
    
        /**
         *
         * @param ack
         * The Ack
         */
        public void setAck(String ack) {
            this.ack = ack;
        }
    
        /**
         *
         * @return
         * The message
         */
        public String getMessage() {
            return message;
        }
    
        /**
         *
         * @param message
         * The Message
         */
        public void setMessage(String message) {
            this.message = message;
        }
    
    
        /**
         *
         * @return
         * The data
         */
        public T getData() {
            return data;
        }
    
        /**
         *
         * @param data
         * The Data
         */
        public void setData(T data) {
            this.data = data;
        }
    }
    

    And call like this

     Call<BaseResponse<SetupDetails>> getSetup(@Query("site_id") int id,@Query("ino") String ii);
    
    0 讨论(0)
提交回复
热议问题