Получение NegativeArraySizeException при анализе JSON из openweathermap
Я пытаюсь получить данные, используя класс Async, но вместо получения данных я получаю исключение NegativeArraySizeException. Хотя все остальное правильно, и я не знаю, какую ошибку я совершил.
Ниже приведен код, который я использую для извлечения данных:
private class FetchData extends AsyncTask<Object, Void, String>
{
@Override
protected String doInBackground(Object... arg0) {
int responseCode = -1;
try
{
URL apiURL = new URL("http://api.openweathermap.org/data/2.5/weather?q=london&mode=json&units=metric");
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONObject jsonResponse = new JSONObject(responseData);
JSONArray weather_icon = jsonResponse.getJSONArray("weather");
JSONObject obj_icon = weather_icon.getJSONObject(0);
String icon = obj_icon.getString("icon");
String status = obj_icon.getString("description");
String location = jsonResponse.getString("name");
JSONObject main = jsonResponse.getJSONObject("main");
String tempreature = main.getString("temp");
String humidity = main.getString("humidity");
String pressure = main.getString("pressure");
pTempreature = tempreature;
pHumidity = humidity;
pPressure = pressure;
pLocation = location;
pStatus = status;
pIcon = icon;
Intent i = new Intent(MainActivity.this, DisplayData.class);
i.putExtra("tem", tempreature);
i.putExtra("ico", icon);
i.putExtra("hum", humidity);
i.putExtra("pre", pressure);
i.putExtra("stat", status);
i.putExtra("loc", location);
startActivity(i);
}
}
catch (MalformedURLException e)
{
Log.e("log_tag","Error In URL"+e.toString());
}
catch (IOException e)
{
Log.e("log_tag","Error In URL"+e.toString());
}
catch (Exception e)
{
Log.e("log_tag","Error In URL"+e.toString());
}
return "Code :"+responseCode;
}
}
1 ответ
Решение
Я не запускал ваш код, но, вероятно, у вас есть проблема с:
char[] charArray = new char[contentLength];
Как я выяснил на этой странице, content-lengtth не установлен для вашего URL, поэтому вы получаете -1 в contentLength. Попробуйте этот код, чтобы получить ваш контент:
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();