0
0

Здраствуйте дрогие друзья!

Недвно возникла проблема при написании кода на джава. Когда запускаю код приложение не работает. пожалуйста помогите с решением данной проблемы.

Исходный код:

package com.example.weatherapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.WeakHashMap;

public class MainActivity extends AppCompatActivity {

private final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q=%s&lang=ru&appid=c8331fd50f41f75720b8fb3bc77104ea&units=metric";

private EditText editTextCity;
private TextView textShowWeather;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextCity = findViewById(R.id.editTextTextCity);
textShowWeather = findViewById(R.id.textShowWeather);
}

public void onClickShowWeather(View view) {
String city = editTextCity.getText().toString().trim();
if(!city.isEmpty()) {
DownloadWeatherTask task = new DownloadWeatherTask();
String url = String.format(WEATHER_URL, city);
task.execute(url);
}
}

private class DownloadWeatherTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
URL url = null;
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();

try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();

while (line != null) {
result.append(line);
line = bufferedReader.readLine();
}
return result.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String city = jsonObject.getString("name");
String temp = jsonObject.getJSONObject("main").getString("temp");
String description = jsonObject.getJSONArray("weather").getJSONObject(0).getString("description");
String weather = String.format("Город: %s\nТемпература: %s\nНа улице: %s", city,temp,description);
textShowWeather.setText(weather);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}


Ибрагим Асланзаде
3 years ago






Еще нет ответов