无法更改匿名类

时间:2015-07-11 16:34:48

标签: java android retrofit anonymous

我是Java和Android开发的新手。我正在尝试为我的网站制作应用。我使用Retrofit连接到我的REST Web服务。

以下是我用于迭代客户ID的一段代码,并且对于每个id,调用以检索与id关联的电子邮件。 authenticateUser方法接收用户名,密码和ID列表(客户ID)。 ID位于mywebsite / api / customers。 电子邮件可在mywebsite / api / customers / 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。请帮忙

2 个答案:

答案 0 :(得分:1)

原因是循环注册回调并且不等待它们完成,因此它也不会等待检查回调是否实际被调用。由于回调没有及时完成,因此在found[0]条件检查之前,他们没有机会将true更改为if

您应该重构代码,以便等待每个回调完成。

答案 1 :(得分:0)

我明白了。这是非常明显和容易的但是因为我对这一切都是新手(或者我可能是愚蠢的:p),我花了很长时间。

我使用了Retrofit的SYNCHRONOUS调用。界面:

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

我在AsyncTask里面这样称呼它:

UserObject user = api.getUser();

希望这可以帮助像我这样的其他新手