I try to connect to the API known openweathermap in Android Studio. I put a piece of code that just gets the answer and writes it to the string:
public class MainActivity extends AppCompatActivity { public String data = "123"; TextView ok; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String city = "Rome,IT"; ok = findViewById(R.id.hello); WeatherHttpClient weather = new WeatherHttpClient(); weather.execute(city); ok.setText(data); } class WeatherHttpClient extends AsyncTask<String, Void, Void> { private static final String API_CODE = "здесь_был_код_подключения"; private static final String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?q="; @Override protected Void doInBackground(String... params) { HttpURLConnection connection = null; InputStream is = null; try { connection = (HttpURLConnection) (new URL(BASE_URL + params[0] + "&APPID=" + API_CODE)).openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(true); connection.connect(); StringBuffer buffer = new StringBuffer(); is = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = bufferedReader.readLine()) != null) { buffer.append(line); } is.close(); connection.disconnect(); data = buffer.toString(); } catch... I receive the answer from API, I see that registers in buffer, and then in data. But in the end, in fact, in the TextView ok is not recorded, there remains the value "123".
I assumed that the order of code execution should be as follows: onCreate runs the execute of the WeatherHttpClient class, it executes doInBackground, the data in it is overridden by the response value, and then the data value goes to TextView (where ok.setText (data) occurs). In fact, I see that in onCreate, the value of ok is set to "123", and only then it goes to WeatherHttpClient, but ok itself is no longer updated by the value of the API response.
Please tell me why this is happening? Purpose: do not display the value of the response on the UI (I understand that it is possible through onPostExecute), namely, save it in data and output it in UI via the data of the onCreate method. PS: in the end, I can pull out the answer differently, but this situation is not clear exactly where I am wrong?
ok.setText(data)runs before the asynchronous class finishes. Nobody will repeat the call of this line after the flow naturally and the value of data in onCreate () will not change - pavlofff