0
i am using retrofit2 to access an API... It turns out I can’t get the data from this API.
I managed to make my code work with this API: (That one), but when I redo the code to use the previous one, I get nullPointer error in Activitymain on the first foreach line that displays the results.
Code:
Mainactivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UdacityService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
UdacityService service = retrofit.create(UdacityService.class);
Call<CharacterCatalog> requestCatalog = service.listCatalog();
requestCatalog.enqueue(new Callback<CharacterCatalog>() {
@Override
public void onResponse(Call<CharacterCatalog> call, Response<CharacterCatalog> response) {
if(!response.isSuccessful()){
Log.e("ERRO", "Erro no servidor (" + response.code() + ")");
}
else {
CharacterCatalog catalog = response.body();
for (Result c : catalog.results){
Log.i("RESULT", String.format("id; %s, name: %s\n",c.id, c.name));
for (Origin o : c.origins){
Log.i("RESULT", String.format("nome; %s, url: %s\n",o.name, o.url));
}
Log.i("RESULT", "/////////////////////////////////////////");
}
}
}
@Override
public void onFailure(Call<CharacterCatalog> call, Throwable t) {
Log.e("ERRO", "Verifique a conexão com a internet (" + t.getMessage() + ")");
}
});
}}
Retofit interface:
public interface ApiService {
public static final String BASE_URL = "https://rickandmortyapi.com/api/";
@GET("character")
Call<CharacterCatalog> listCatalog();
}
List with the results:
public class CharacterCatalog {
public List<Result> results;
}
Class Result
public class Result {
public String id;
public String name;
public String status;
public String species;
public String gender;
public List<Origin> origins;
}
Class Origin:
public class Result {
public String id;
public String name;
public String status;
public String species;
public String gender;
public List<Origin> origins;
}
Someone can help me with this mistake?
Any error in logcat?
– Leonardo Lima
Appears, but I think it is not related to the app, keeps giving audio emulator error..
– Marcello Sousa
Apparently the api does not return an array
origins
and yes an objectorigin
in Character. nullpointer is in this variable?– Leonardo Lima
That’s right!! I took the list and left to receive only the object and it worked out! thanks there.
– Marcello Sousa