我使用改造的android库进行rest api调用。我将RestClient实现为单例类,如下所示
RestClient.java
public class RestClient {
private static Api REST_CLIENT;
private static String BASE_URL = "base_url";
public RestClient() {}
public static Api getInstance() {
if (REST_CLIENT != null) {
setupRestClient();
}
return REST_CLIENT;
}
private static void setupRestClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
REST_CLIENT = restAdapter.create(Api.class);
}
}
然后我用
打电话给api Api api = RestClient.getInstance();
api.getLoginResponse(usernameText, passwordText, android_id, new Callback<LoginResponse>() {
@Override
public void success(LoginResponse loginResponse, Response response) {
Toast.makeText(getApplicationContext(), loginResponse.getToken(), Toast.LENGTH_SHORT).show();
}
@Override
public void failure(RetrofitError error) {
}
});
但是当我调试实例api
的值总是为null并得到 java.lang.NullPointerException:尝试在logcat中调用接口方法错误
答案 0 :(得分:2)
您的If条件在getInstance()方法中是错误的。请检查一下。
public class RestClient {
private static Api REST_CLIENT;
private static String BASE_URL = "base_url";
public RestClient() {}
public static Api getInstance() {
if (REST_CLIENT == null) {
setupRestClient();
}
return REST_CLIENT;
}
private static void setupRestClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
REST_CLIENT = restAdapter.create(Api.class);
}
}