我试图使用Retrofit2调用API获取数据。当我打开我的应用程序,它立即崩溃。我尝试了很多解决方案。我使用邮差,仍然看到所有的数据是json格式。有人能帮我吗?非常感谢
这是我的日志
Process: tdtu.phongtrosinhvien, PID: 4992
java.lang.NullPointerException: Attempt to invoke interface method 'retrofit2.Call tdtu.phongtrosinhvien.Mode.API.TimTroApi.getdatanewPost()' on a null object reference
ApiClient
public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.addInterceptor(interceptor).build();
Gson gson = new GsonBuilder()
.create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
}
return retrofit;
}
}
aip调用接口
@POST("getDataNewlyPostedRoom.php")
Call<List<Post>> getdatanewPost() ;
和这里的Home片段。
private void loadDataNewPost() {
TimTroApi.getdatanewPost().enqueue(new Callback<List<Post>>() {
@Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
if (response.isSuccessful()) {
postArrayList = (ArrayList<Post>) response.body();
getDataNewPost(postArrayList);
swipeContainer.setRefreshing(false);
}
}
@Override
public void onFailure(Call<List<Post>> call, Throwable t) {
Log.e("aaa",t.getMessage());
swipeContainer.setRefreshing(false);
}
});
}
问题是你试图调用对象中未初始化的方法,你应该阅读改造文档
首先创建一个Service,调用您的请求,下面是Retrofit文档中的示例。
GitHubService service = retrofit.create(GitHubService.class);
Call<List<Repo>> repos = service.listRepos("octocat");
改造医生