partiz
partiz

Reputation: 1216

pass variable to Nested methods in Java (android) and return it

Hi there I have a method like this, I want declate 'userList' and pass it to nested method,and then return it outside of that nested method.

something like this:

private List<User> getUsers() {
List<User> userList = new ArrayList<>();

@Override
public void onResponse(JSONObject response) 
{
    for(int i=0; i < 100; i++)
    {
        ...
        userList.add(user);
    }
});
return userList;
}

how can pass userlist to onResponse(JSONObject response) and then return it outside of that function?

Upvotes: 1

Views: 372

Answers (1)

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

@Override
public void onResponse(JSONObject response) ...
// void return type == cannot return

means that you are implementing this abstract method (OkHttp/Volley/Retrofit, whatever). So (technically) you can't change its signature, which means that you cannot return anything from this callback.

The only thing you can do is use a member variable, to whom you will assign the results coming from your callback method :

// Member variable of this class
List<User> userList = new ArrayList<>();

@Override
public void onResponse(JSONObject response) {
    for (int i = 0; i < 100; i++) {
        // Add elements to your arraylist
        userList.add(user);
    }

    /* That's it, your arraylist is updated. Now call whatever method that
     was supposed to retrieve the result (the arraylist) of this callback */
}

Upvotes: 2

Related Questions