【发布时间】:2018-05-24 11:47:43
【问题描述】:
我不知道问题到底出在哪里,只要我登录到来自 api 的信息,应用程序就会崩溃。 这是代码。我不知道代码是否过时,我正在运行最新版本的 Android Studio。
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("main", jsonPart.getString("main"));
Log.i("description", jsonPart.getString("description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
如果你能帮助我,那就太棒了,我很高兴能制作自己的天气应用程序!
【问题讨论】:
标签: java android api openweathermap