Well, the fact is that I just want to show the name of the countries in a list, but I do not know how to get the name only:
This is the main class:
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();
}
});
}
The interface:
public interface ICountryService {
String ENDPOINT = "https://restcountries.eu";
@GET("/rest/v1/all")
Call<List<Country>> getCountry();
}
The Country class is very extensive but of the whole class I just want to show the list of countries. How do I do it?:
public class Country {
/**
*
* (Required)
*
*/
@SerializedName("name")
@Expose
private String name;
Of course, this class has gotters and setters generated
OnResponse method (I leave here this implementation already given in the solution but more adapted to the exercise):
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();
}
});