Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the value from inner class to outer class?

What I want to do is when onSuccess method executed, the queryLogin return true,while if onFailuer method executed , the queryLogin return false; But as you know, in java, I cannot modify an outer class value from the inner class. So I just wonder how can I solve the problem and achieve my aim.

 public static boolean queryLogin(String username, String passowrd){
    boolean isSuccess = false;
    params.put("username", username);
    params.put("password", passowrd);
    VStarRestClient.post(LOGIN_URL, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            isSuccess = true;//cannot
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            String responseContent = new String(responseBody);
            isSuccess = false;//cannot
        }
    });

    return isSuccess;
}
like image 376
Shuai Wang Avatar asked Dec 28 '25 18:12

Shuai Wang


2 Answers

You're trying to mix synchronous and asynchronous behaviour here, which cannot work.

The post() method just triggers a HTTP post and execution of your login method continues to its end without waiting for the result of that post. That's what the AsyncHttpResponseHandler is here for. It is called when the reply to the post() arrives.

Network activities (and all other tasks, which might take a long time) are always asynchonously to not freeze the UI of your app.

like image 195
Ridcully Avatar answered Dec 30 '25 08:12

Ridcully


You should add a specific method to your outer class, and call it from inner class. This method should receive an argument and simply setup an outer class member variable; then use that variable as you wish.

like image 45
Andrey Kopeyko Avatar answered Dec 30 '25 08:12

Andrey Kopeyko