2015-09-04 78 views
-3

我使用retrofit android庫進行其他api調用。我實現了作爲RESTClient實現一個單獨的類如下改造Android使錯誤java.lang.NullPointerException:嘗試調用接口方法

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 = 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,但,當我調試實例值api總是空,並得到java.lang.NullPointerException:試圖調用logcat中的接口方法錯誤

+0

我相信,如果條件是在'getInstance'方法落後:'如果(REST_CLIENT!= NULL)'意味着如果'REST_CLIENT'已經初始化代碼將只運行,否則,你回來正如我們所討論的那樣,REST_CLIENT'總是'null'。 –

+0

[Retrofit android not working and has no error]可能的重複(http://stackoverflow.com/questions/32389584/retrofit-android-not-working-and-has-no-error) –

回答

2

如果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); 
     } 
    } 
相關問題