我正在尝试使用复古拟合,但没有调用onResponse和onFailure。我也没有得到任何例外。我搞不懂我哪里做错了。如果你能发现一些东西,我将不胜感激。
Update -我在OnResponse方法中得到空指针异常。
Url - https://jsonplaceholder.typicode.com/posts/
API客户端
public class ApiClient {
public static final String BASE_URL_TWO = "https://jsonplaceholder.typicode.com/posts/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient()
{
if(retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL_TWO).
addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}ApiInterface
public interface ApiInterface {
@GET("/posts")
Call<List<DemoJSONAPIData>> getDemoData();
}ApiCalls
public class ApiCalls implements IApiCalls{
private ApiInterface apiInterface;
private List<DemoJSONAPIData> demoJSONAPIDatas;
@Override
public List<DemoJSONAPIData> getDemoData() {
try{
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<List<DemoJSONAPIData>> call = apiInterface.getDemoData();
call.enqueue(new Callback<List<DemoJSONAPIData>>() {
//Skips out of try catch, no exception being caught
@Override
public void onResponse(Call<List<DemoJSONAPIData>> call, Response<List<DemoJSONAPIData>> response) {
//UPDATE - I am getting NULL pointer here.
demoJSONAPIDatas = response.body();
Log.d("demoJSONAPIDatas", demoJSONAPIDatas.toString());
for(DemoJSONAPIData demoJSONAPIData: demoJSONAPIDatas){
Log.d("UserId", demoJSONAPIData.getId());
Log.d("Title", demoJSONAPIData.getTitle());
}
}
@Override
public void onFailure(Call<List<DemoJSONAPIData>> call, Throwable t) {
//IS not called
}
});
}catch (Exception e){
System.out.println("Error " + e.getMessage());
}
return demoJSONAPIDatas;
}
}DemoJSONAPIData
public class DemoJSONAPIData {
@SerializedName("userId")
private String UserId;
@SerializedName("id")
private String Id;
@SerializedName("title")
private String Title;
@SerializedName("body")
private String Body;
public String getUserId() {
return UserId;
}
public String getId() {
return Id;
}
public String getTitle() {
return Title;
}
public String getBody() {
return Body;
}
}像这样使用它
List<DemoJSONAPIData> demoJSONAPIDatas = apiCalls.getDemoData();请指出我哪里做错了。
谢谢R
发布于 2017-11-23 01:30:46
这是因为Call.enqueue是异步的。它不会在返回之前发出请求;它会在另一个线程中发起请求,然后立即返回。当它返回时,demoJSONAPIDatas仍然是null,因为还没有发生任何事情。所以这就是
List<DemoJSONAPIData> demoJSONAPIDatas = apiCalls.getDemoData();不会起作用。
发布于 2017-11-23 03:10:17
问题出在您的ApiClient和interface.make下面的更改。
基本need需要像下面的一样进行更改
public class ApiClient {
public static final String BASE_URL_TWO = "https://jsonplaceholder.typicode.com/";
public static Retrofit retrofit = null;
public static Retrofit getApiClient()
{
if(retrofit == null)
{
retrofit = new Retrofit.Builder().baseUrl(BASE_URL_TWO).
addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}get()方法也将更改为
public interface ApiInterface {
@GET("posts")
Call<List<DemoJSONAPIData>> getDemoData();
}更新
private List<DemoJSONAPIData> demoJSONAPIDatas=new ArrayList<>();https://stackoverflow.com/questions/47440206
复制相似问题