修复 IllegalStateException

Fixing IllegalStateException

try {
        Response response = client.newCall(request).execute();
        getStockInfoFromJSON(response.body().string());
    } catch (IOException | JSONException | IllegalStateException e) {
        Log.i("GraphAsyncTask", e.toString());
    }

对于上面看到的代码块,我现在收到 IllegalStateException。我最初没有收到此错误。我需要更改 API,因此请求对象中的 URL 不同。创建 Response 对象后出现错误。 getStockInfoFromJSON() 方法不是 运行。我知道它不是 运行 因为我在一开始就放置了一个日志语句并且它没有显示在控制台中。我怎样才能避免抛出这个错误。

private void getStockInfoFromJSON(String JsonString)
        throws JSONException {
    Log.i("MSA JSON string", JsonString);
    MyStocksActivity.StockData = new ArrayList<>();
    JSONObject Json = new JSONObject(JsonString);
    JSONObject StockInfo = Json.getJSONObject("Time Series (Daily)");
    JSONArray array = new JSONArray();
    StockInfo.toJSONArray(array);
    Log.i("MSA", "JSON array " + StockInfo.toString());

    for (int i = 0; i < array.length(); i++) {
        StockData datum = new StockData();
        JSONObject stockPrice = array.getJSONObject(i);
        Log.i("stock price array", stockPrice.toString());
        String date = array.getString(i);
        Log.i("date", date);
        String[] stringDate = date.split("-");
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(stringDate[0]),
                Integer.parseInt(stringDate[1]), Integer.parseInt(stringDate[2].substring(0, 2)));
        Log.i("cal", cal.toString());
        datum.date = cal.getTimeInMillis();
        datum.price = array.getDouble(3);
        datum.CalDate = date.split(" ")[0];
        MyStocksActivity.StockData.add(datum);

    }
}

这是我收到的错误消息。

07-03 15:05:29.586 27929-28167/com.example.sam_chordas.stockhawk I/GraphAsyncTask: java.lang.IllegalStateException: closed

您是否正在阅读响应正文两次?您只能调用 string() 一次。