Tengo código siguiente
public void callMatchListApi() {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<NewMatchList> apiList = apiService.getNewMatchListCallListCall(API_KEY);
apiList.enqueue(new Callback<NewMatchList>() {
@Override
public void onResponse(Call<NewMatchList> call, Response<NewMatchList> response) {
//NewMatchList newMatchList=response.body();
Log.d("ApiCall", String.valueOf(response.body().getMatchList().get(0).getTeam1()));
// Log.d("ApiCall_22",newMatchList.getMatchList().get(0).getTeam1());
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<NewMatchList> call, Throwable t) {
Log.d("ApiCall_Error", t.toString());
}
});
}
Aquí NewMatchList
es una clase modal pojo. Por lo tanto, necesito hacer esto NewMatchList
en objeto dinámico para poder pasarlo en callMatchListApi()
a reutilizable. Intenté reemplazar NewMatchList para hacer referencia a la referencia en el parámetro y también en el nombre de la Clase, pero arrojará un error. Dado que soy nuevo en Android, ¿alguien puede ayudarme a solucionar este problema?
3 respuestas
También puedes usar genéricos si crees que Object
no te ayuda:
public <T> void callApi(T classz) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<T> apiList = apiService.getNewMatchListCallListCall(API_KEY);
apiList.enqueue(new Callback<T>() {
@Override
public void onResponse(Call<T> call, Response<T> response) {
//T T=response.body();
Log.d("ApiCall", String.valueOf(response.body().getMatchList().get(0).getTeam1()));
// Log.d("ApiCall_22",T.getMatchList().get(0).getTeam1());
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
processResponse(response, classz);
}
@Override
public void onFailure(Call<T> call, Throwable t) {
Log.d("ApiCall_Error", t.toString());
}
});
}
private <T> void processResponse(Response<T> response, T classz) {
if (classz instanceof OneModel) {
processOneModelResponse(response);
}
if (classz instanceof AnotherModel) {
processOAnotherModelResponse(response);
}
}
En lugar de su objeto NewMatchList
, tenemos un tipo genérico T
y podemos pasarlo como parámetro.
Y ahora puede llamar al método de la siguiente manera:
callApi(NewMatchList.class)
Una cosa que es posible que desee refactorizar un poco es el apiService.getNewMatchListCallListCall(API_KEY)
. Es posible que desee extraer esa llamada al método en algún lugar fuera antes de llamar al método, porque supongo que su apiService
tiene diferentes métodos con diferentes tipos Call
.
Actualizar : Puede agregar un método para procesar la lógica de negocios para cada respuesta que obtenga. Algo así como processResponse
y luego procesará cada tipo específico de modelo (usando instance of
) en su método específico (processOneModelResponse
, processAnotherModelResponse
)
Para reutilizar, intente usar el tipo genérico Object
en el tipo de respuesta e intente analizar que
public void callMatchListApi() {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<Object> apiList = apiService.getNewMatchListCallListCall(API_KEY);
apiList.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
//NewMatchList newMatchList=response.body();
Log.d("ApiCall", String.valueOf(response.body().getMatchList().get(0).getTeam1()));
// Log.d("ApiCall_22",newMatchList.getMatchList().get(0).getTeam1());
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Object> call, Throwable t) {
Log.d("ApiCall_Error", t.toString());
}
});
}
Hola, sugiero usar RxJava con el servicio Retrofit.
App build.gradle
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.1.8'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile group: 'com.squareup.retrofit2', name: 'converter-jackson', version: '2.3.0'
Clase ApiHelper
public class ApiHelper {
public static ApiService getService() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.MINUTES)
.readTimeout(5, TimeUnit.MINUTES)
.writeTimeout(5,TimeUnit.MINUTES)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConstants.BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
return retrofit.create(ApiService.class);
}
}
Clase ApiService
public interface ApiService {
@POST("update_token.php")
@FormUrlEncoded
Single<ApiRespBean> updateToken(@Field("manufacture") String manufacture, @Field("model") String model, @Field("device_id") String device_id, @Field("fcm_token") String fcm_token);
@GET("get_all_history.php")
Single<HistoryRespBean> getAppHistory();
@POST("update_suggest_name.php")
@FormUrlEncoded
Single<ApiRespBean> updateSuggestName(@Field("image_id") int image_id,@Field("suggest_name") String suggest_name);
}
Clase ApiRespBean
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"status_code",
"message",
"data"
})
public class ApiRespBean {
@JsonProperty("status_code")
private Integer statusCode;
@JsonProperty("message")
private String message;
@JsonProperty("data")
private Object data;
@JsonProperty("status_code")
public Integer getStatusCode() {
return statusCode;
}
@JsonProperty("status_code")
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
@JsonProperty("message")
public String getMessage() {
return message;
}
@JsonProperty("message")
public void setMessage(String message) {
this.message = message;
}
@JsonProperty("data")
public Object getData() {
return data;
}
@JsonProperty("data")
public void setData(Object data) {
this.data = data;
}
}
Clase MainActivity
ApiHelper.getService().updateToken(Build.MANUFACTURER, Build.MODEL, Build.ID, fcmToken)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(apiRespBean -> {
Log.d("TAG","success");
},
throwable -> {
Log.d("TAG","error");
});
Nuevas preguntas
java
Java es un lenguaje de programación de alto nivel. Utilice esta etiqueta cuando tenga problemas para usar o comprender el idioma en sí. Esta etiqueta rara vez se usa sola y se usa con mayor frecuencia junto con [spring], [spring-boot], [jakarta-ee], [android], [javafx], [hadoop], [gradle] y [maven].