Все сервисы Хабра
Сообщество IT-специалистов
Ответы на любые вопросы об IT
Профессиональное развитие в IT
Закрыть
Задать вопрос
manah91
0
вклад
1
вопрос
0
ответов
0%
решений
Комментарии
Информация
Ответы
Вопросы
Комментарии
Подписки
Нравится
Что означает ошибка java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference?
manah91
@manah91
Автор вопроса
Код приложения:
package com.hfad.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;
public class MainActivity extends AppCompatActivity {
private final String WEATHER_URL = "
http://api.openweathermap.org/data/2.5/weather?q=%...
";
private EditText editTextCity;
private TextView textViewWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextCity = findViewById(R.id.editTextCity);
textViewWeather = findViewById(R.id.textViewWeather);
}
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{
@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 reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
result.append(line);
line = reader.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);
textViewWeather.setText(weather);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Написано
более трёх лет назад
Войдите на сайт
Чтобы задать вопрос и получить на него квалифицированный ответ.
Войти через центр авторизации
Закрыть
Реклама
package com.hfad.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;
public class MainActivity extends AppCompatActivity {
private final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q=%...";
private EditText editTextCity;
private TextView textViewWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextCity = findViewById(R.id.editTextCity);
textViewWeather = findViewById(R.id.textViewWeather);
}
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{
@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 reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
result.append(line);
line = reader.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);
textViewWeather.setText(weather);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}