Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

336
Vistas
How can I return data in method from Retrofit onResponse?

I'm new with retrofit and I want to make my getData method to return a feature object. What is the easiest way to do that?

DataService.java

public class DataService {

    private static final String TAG = MainActivity.class.getSimpleName();
    private final ApiClient apiClient;

    public DataService() {
        apiClient = new ApiClientFactory().createApiClient();
    }

    public List<Feature> getData(){

        apiClient.getData().enqueue(new Callback<DataResponse>() {

            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                List<Feature> features = response.body().getFeatures();
                Log.d(TAG, "Data successfully downloaded");
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Log.e(TAG, t.toString());
            }
        });
        //I need to return features in getData method
    }
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can't return, you must "call back".

Extract that inner Callback class to a parameter.

public void getData(Callback<DataResponse> callback){
    apiClient.getData().enqueue(callback);
}

In your other code

// DataService service = ...;

// Define Callback
Callback<DataResponse> responseCallback = new Callback<DataResponse>() {

    @Override
    public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
        List<Feature> features = response.body().getFeatures();
        Log.d(TAG, "Data successfully downloaded");

        // Data is returned here
        for (Feature f: features) {
            Log.d("feature", String.valueOf(f)); // for example
        }
    }

    @Override
    public void onFailure(Call<DataResponse> call, Throwable t) {
        Log.e(TAG, t.toString());
    }
};

// Call it
service.getData(responseCallback);

You can also do service.getData(new Callback<DataResponse>() { ... });

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda