我正在使用改造来访问 API,但我无法获取此 API 的数据
API 链接
我能够使我的代码与这个 API 一起工作:(这个),但是当我重做代码以使用前一个代码时,我在我用来显示结果的第一行的 ActivityMain 中得到了 nullPointer 错误。
代码:
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() + ")");
}
});
}}
Interface retofit:
public interface ApiService {
public static final String BASE_URL = "https://rickandmortyapi.com/api/";
@GET("character")
Call<CharacterCatalog> listCatalog();
}
列出结果:
public class CharacterCatalog {
public List<Result> results;
}
有人可以帮我解决这个错误吗?
长风秋雁
慕哥9229398
相关分类