Good day, gentlemen! Help me to understand.

private AccountInfo getAccountInfo() { final AccountInfo accountInfo = new AccountInfo(); VKRequest profileInfo1 = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, Constants.PHOTO_MAX_ORIG)); profileInfo1.executeWithListener(new VKRequest.VKRequestListener() { @Override public void onComplete(VKResponse response) { //Do complete stuff try { JSONArray responseArray = response.json.getJSONArray(Constants.RESPONSE); JSONObject obj = responseArray.getJSONObject(0); accountInfo.userName = obj.getString(Constants.FIRST_NAME); accountInfo.userLastname = obj.getString(Constants.LAST_NAME); accountInfo.avatarUrl = obj.getString(Constants.PHOTO_MAX_ORIG); tvUserFullName.setText(accountInfo.userName + " " + accountInfo.userLastname); Log.d(TAG, "Name = " + accountInfo.userName); Log.d(TAG, "LastName = " + accountInfo.userLastname); Log.d(TAG, "avatarURL = " + accountInfo.avatarUrl); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onError(VKError error) { //Do error stuff Toast.makeText(UserInterface.this, "Не удалось загрузить данные из Вашего аккаунта.", Toast.LENGTH_SHORT).show(); } @Override public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) { //I don't really believe in progress } }); return accountInfo; null/null/null } 

The problem is that the string

 return accountInfo; 

and tvUserFullName.setText(accountInfo.userName + " " + accountInfo.userLastname); is executed before the response from the server comes

 accountInfo.userName = obj.getString(Constants.FIRST_NAME); 

And the program takes off from NullPointerException.

    1 answer 1

    You cannot force a synchronous method to immediately return data for which it takes time.

    Also, you cannot force a method to wait while a request is being executed. Especially since he may not be successful.

    You need to alter the logic in such a way as to process the result of the request only after its execution.

    • and what are the methods, methods that will only work when the server responds ??? - S.TertJ
    • @ S.TertJ, when the request is completed, onComplete and onError that you already have in the code are called - YuriSPb