Pues eso el caso es que solo quiero mostrar el nombre de los países en una lista, pero no sé cómo obtener solo el nombre:
Esta es la clase principal:
listView = (ListView) findViewById(R.id.list_view);
textView = (TextView) findViewById(R.id.text_view);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ICountryService.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
.build();
ICountryService service = retrofit.create(ICountryService.class);
Call<List<Country>> call = service.getCountry();
call.enqueue(new Callback<List<Country>>() {
@Override
public void onResponse(Response<List<Country>> response, Retrofit retrofit) {
if (response.isSuccess()) {
List<Country> countryList = response.body();
ArrayAdapter<Country> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, countryList);
listView.setAdapter(adapter);
} else {
Toast.makeText(MainActivity.this, "Error: " + response.code(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
La interface:
public interface ICountryService {
String ENDPOINT = "https://restcountries.eu";
@GET("/rest/v1/all")
Call<List<Country>> getCountry();
}
La clase Country es muy extensa pero de toda la clase solo quiero mostrar la lista de países. ¿Cómo lo hago?:
public class Country {
/**
*
* (Required)
*
*/
@SerializedName("name")
@Expose
private String name;
Por supuesto, esta clase tiene generados los getter y setters
Método onResponse(dejo aquí esta implementación dada ya en la solución pero más adaptada al ejercicio):
call.enqueue(new Callback<List<Country>>() {
@Override
public void onResponse(Response<List<Country>> response, Retrofit retrofit) {
if (response.isSuccess()) {
List<Country> countryList = response.body();
List<String> listaNombres = new ArrayList<String>();
for (Country c : countryList
) {
listaNombres.add(c.getName());
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, listaNombres);
listView.setAdapter(adapter);
}
} else {
Toast.makeText(MainActivity.this, "Error: " + response.code(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(MainActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_LONG).show();
}
});