改进 - GET后的null对象

时间:2018-06-05 08:49:10

标签: java android get retrofit

我想从数据库中获取所有用户并通过登录列表查找用户。 我总是得到信息,我的actualUser为null。我也尝试显示Log.d(" msg",usr.getLogin()),但它也是同样的问题。

我有:

private List<User> users = new ArrayList<>();
private User actualUser;

//Init API
Retrofit retrofit = RetrofitClient.getInstance();
restAPI = retrofit.create(RESTAPInterface.class);

newDeviceAcceptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //get user info
                getAllUsers();
                for(User usr: users){
                    if(UserCredentials.getInstance().getUsername().equals(usr.getLogin())) {
                        actualUser = new User(usr.getId(), usr.getLogin(), usr.getPassword());
                        Log.d("mojlogin", actualUser.getLogin());
                        break;
                    }
                }

public void getAllUsers(){
        compositeDisposable.add(restAPI.getUsers("Bearer " + TokenHolder.getInstance().getToken())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<List<User>>() {
            @Override
            public void accept(List<User> users) throws Exception {
                initializeUsers(users);
            }
        }));
    }

public void initializeUsers(List<User> users){ this.users = users; }

1 个答案:

答案 0 :(得分:0)

我认为你必须在getAllUsers中获得initializeUsers的实际用户调用方法。

public void getAllUsers(){
    compositeDisposable.add(restAPI.getUsers("Bearer " + TokenHolder.getInstance().getToken())
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<List<User>>() {
        @Override
        public void accept(List<User> users) throws Exception {
            Log.d("TAG", "users=>"+users.size());
            initializeUsers(users);
            for(User usr: users){
                if(UserCredentials.getInstance().getUsername().equals(usr.getLogin())) {
                    actualUser = new User(usr.getId(), usr.getLogin(), usr.getPassword());
                    Log.d("mojlogin", actualUser.getLogin());
                    break;
                }
            }
        }
    }));
}