私はRetrofitでhttps://newsapi.org/v1/articles
からJSONデータを取得しようとしていますが、これは初めてのことです。これまではかなり混乱していました。nullオブジェクトを取得するのはなぜですか?
私が知る限り、私は成功した接続を確立することができました。しかし、何らかの理由で私がまだ識別できなかったため、RetrofitはJSON文字列のデータをNewsAPI
クラスにマッピングしません。
私が現在使用しているコードを投稿し、誰かがこれを理解するのを助けることを期待しています。ありがとう!
Activity.java
:
final TextView tvTest = (TextView) findViewById(R.id.tvTest);
String url = "https://newsapi.org";
NewsAPI_Interface client = NewsAPI_Adapter.createService(NewsAPI_Interface.class);
Call<List<NewsAPI>> call = client.getData("techcrunch", "APIkeygoeshere");
call.enqueue(new Callback<List<NewsAPI>>() {
@Override
public void onResponse(Call<List<NewsAPI>> call, Response<List<NewsAPI>> response) {
if (response.body() != null) {
tvTest.setText(response.body().toString());
for (NewsAPI news: response.body()) {
System.out.println(news.source + " (" + news.status + ")");
tvTest.setText(news.source + " (" + news.status + ")");
}
} else {
tvTest.setText("It's null, " + response.errorBody().toString() + ", " + call.request().url());
}
}
@Override
public void onFailure(Call<List<NewsAPI>> call, Throwable t) {
tvTest.setText("An error ocurred!");
}
});
NewsAPI.java
:
public class NewsAPI {
String status;
String source;
public NewsAPI (String status, String source) {
this.status = status;
this.source = source;
}
}
NewsAPI_Interface.java
:
public interface NewsAPI_Interface {
@GET("/v1/articles")
Call<List<NewsAPI>> getData(@Query("source") String source, @Query("api_Key") String api_key);
}
NewsAPI_Adapter.java
:
私が思い出したように、 'onResponse'メソッドから' response.body() 'を1回しか使用できません。 –
あなたはproguardを使用していますか? –
また、私が右を読んでいるなら '@Query(" api_Key ")'は 'apiKey'でなければなりません。 https://newsapi.org/ –