我正在使用改型来访问API,但无法获取该API的数据
我能够使我的代码使用以下API:(This),但是当我重做代码以使用上一个代码时,我在第一个foreach行中的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;
}
班级成绩
public class Result {
public String id;
public String name;
public String status;
public String species;
public String gender;
public List<Origin> origins;
}
类来源:
public class Result {
public String id;
public String name;
public String status;
public String species;
public String gender;
public List<Origin> origins;
}
有人可以帮助我解决这个错误吗?
答案 0 :(得分:0)
请验证您是否对数据类使用了这种格式
@SerializedName("id")
private Integer id;
@SerializedName("name")
private String name;
@SerializedName("status")
private String status;
@SerializedName("species")
private String species;
@SerializedName("type")
private String type;
@SerializedName("gender")
private String gender;
@SerializedName("origin")
private Origin origin;
@SerializedName("location")
private Location location;
@SerializedName("image")
private String image;
@SerializedName("episode")
private List<String> episode = null;
@SerializedName("url")
private String url;
@SerializedName("created")
private String created;
检查以下URL以创建POJOS:http://www.jsonschema2pojo.org/ 并且请确保您实际上正在连接到服务器,并且请确保您从服务器获得了200个答案
答案 1 :(得分:0)
感谢帮助人员,但我解决了问题...在我的课程结果中,我使用的是来源列表,但API仅返回一个对象...我只删除了列表类型。