2015-07-11 25 views
0

我對Java和Android開發相當陌生。我正在爲我的網站製作一個應用程序。我正在使用Retrofit連接到我的REST Web服務。無法更改來自匿名類的變量

以下是我用來遍歷客戶ID和每個ID的一段代碼,我們打電話來檢索與ID相關的電子郵件。 authenticateUser方法接收用戶名,密碼和ID列表(Customer ID)。 ID位於mywebsite/api/customers。 的電子郵件可在mywebsite/API /客戶/ ID

public class Authentication { 

    private static String receivedEmail; 
    public static boolean authenticateUser(List<Integer> ids, final String username, String pass) { 
     RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MainActivity.ENDPOINT).build(); 
     AuthenticationUsernameAPI api = adapter.create(AuthenticationUsernameAPI.class); 
     final boolean[] found = {false}; 
     for (Integer id: ids) { 
      if (!found[0]) { 
       api.getUserEmail(id.toString(), new Callback<CustomerLoginEmail>() { 
        @Override 
        public void success(CustomerLoginEmail customerLoginEmail, Response response) { 
         receivedEmail = customerLoginEmail.getCustomer().getEmail().toString(); 
         if (receivedEmail.compareTo(username) == 0) {       
          found[0] = true; 
         } 
        } 

        @Override 
        public void failure(RetrofitError error) { 
         Log.d("ERROR", error.getMessage()); 
        } 
       }); 
      } else { 
       return true; 
      } 
     } 
     return false; 
    }  
} 

的方法authenticateUser總是返回false。請幫忙

回答

0

我想通了。這是非常明顯和容易的,但因爲我對這一切都很陌生(或者我很愚蠢:p),這花了我相當長的一段時間。

我使用了Retrofit的SYNCHRONOUS調用。接口:

@GET("/user/{id}") 
UserObject getUser(@Path("id") int id); 

和我把它叫做裏面的AsyncTask是這樣的:

UserObject user = api.getUser(); 

希望這有助於任何其他新手像我一樣

1

原因是循環註冊回調,並不等待它們完成,所以它也不會等待檢查回調是否被實際調用。由於回調未能及時完成,因此在通過if條件進行檢查之前,他們沒有機會將found[0]更改爲true

您應該重構代碼,等待每個回調完成。