Java/Android: java.lang.OutOfMemoryError while building a JSON object

前端 未结 4 1405
情书的邮戳
情书的邮戳 2020-12-16 22:46

I am importing JSON data from a public database URI http://data.seattle.gov/api/views/3k2p-39jp/rows.json and the rows go as far as 445454. Using the following code I am co

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 23:19

    I did it a bit differently, My JSON code was waiting for status, which comes towards the end. So I modified the code to return earlier.

    // try to get formattedAddress without reading the entire JSON
            String formattedAddress;
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
                formattedAddress = ((String) ((JSONObject) new JSONObject(
                        jsonResults.toString()).getJSONArray("results").get(0))
                        .get("formatted_address"));
                if (formattedAddress != null) {
                    Log.i("Taxeeta", "Saved memory, returned early from json") ;
                    return formattedAddress;
                }               
            }
    JSONObject statusObj = new JSONObject(jsonResults.toString());
            String status = (String) (statusObj.optString("status"));
            if (status.toLowerCase().equals("ok")) {
                formattedAddress = ((String) ((JSONObject) new JSONObject(
                        jsonResults.toString()).getJSONArray("results").get(0))
                        .get("formatted_address"));
                if (formattedAddress != null) {
                    Log.w("Taxeeta", "Did not saved memory, returned late from json") ;
                    return formattedAddress;
                }           
            } 
    

提交回复
热议问题