Android Retrofit请求如何在主线程中获得改进响应

时间:2017-12-02 23:44:13

标签: java android multithreading nullpointerexception retrofit

我使用retrofit来正确获取响应,然后我将响应传递给响应体中的对象,而它无法在UI线程中获取对象,有一个NullPointerException错误,我认为它是异步请求的问题,我该如何避免这个问题?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.button);

    util = new Util(this);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            util.login("sdjfl@gmail.com", "sdjflsdkf");

            // There is a NullPointerException? How Can I
            // use this methond correctly in this way?
            Log.d("user", util.getUserInfo().toString());
        }
    });
}

public class Util {
    private UserInfo userInfo;

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void login(final String email, final String password) {
        Call<UserInfo> loginCall = apiInterface.login(email, password);
        loginCall.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                userInfo = response.body();
        }

        @Override
        public void onFailure(Call<UserInfo> call, Throwable t) {
        }
    });
}

1 个答案:

答案 0 :(得分:0)

将此行移至onResponse()

Log.d("user", util.getUserInfo().toString());

您正在获取用户信息对象,在您尝试访问它时它为空

喜欢那个

public class Util {
    public interface Callback {
        void onResponse(UserInfo info);
    }
    private UserInfo userInfo;

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void login(final String email, final String password, final Callback callback) {
        Call<UserInfo> loginCall = apiInterface.login(email, password);
        loginCall.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                userInfo = response.body();
                callback.onResponse(userInfo);
                Log.d("user", userInfo.toString());
        }

        @Override
        public void onFailure(Call<UserInfo> call, Throwable t) {
        }
    });
}

以下是你如何使用它

Util.login("email", "password", new Util.Callback() {
   void onResponse(User info) {
       // Update UI
   }
});

请注意,此回调可能会泄漏内存,请确保在保留当前活动/片段时将其清除。