简体   繁体   中英

Variable is still null when assigning it a value

So I have this code:

String query = null;

public String createConnection() {

    new NetworkRequest(new ResultFromAsync() {
        @Override
        public void taskCompleted(String result) {
            query = result;
        }
    }).execute();

    return query;
}

I am following the MVP design pattern, it is called from my View which upon a Button Click event it calls this method which executes and creates a network request from the Model and then retrieves the JSON as a String, when debugging on line "query = result;" it actually assigns the what is stored in the result variable to the query but when it gets to the line "return query;"it equals to null.

Does anyone understand why it is setting the query to null when it had been assigned to a value of the result variable?

Your method that assigns a value to query is executed asynchronously, meaning that calling execute() won't block the current thread until the asynchronous request completes, but returns immediately. The value of your variable is still null at that time. You cannot return a value you don't have yet.

Consider calling the code that requires the value inside the taskCompleted() callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM