改造android make error java.lang.NullPointerException:尝试调用接口方法

时间:2015-09-04 04:53:03

标签: java android retrofit

我使用改造的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中调用接口方法错误

1 个答案:

答案 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);
        }
    }