Getting Out of Memory Error even for a small JSON Response

195 Views Asked by At

The following is the code to get the JSON response from the URL.I'm using AsyncTask to download the response.From the logcat output, the error is shown in readFromStream Method.

    private class MovieAsyncTask extends AsyncTask<String, Void, List<Movie>>{
    @Override
    protected List<Movie> doInBackground(String... urls) {
        URL url = createUrl(urls[0]);

        String jsonresponse = "";

        try{
            jsonresponse = makeHttpRequest(url);
        }
        catch (IOException e){

        }


        List<Movie> movieList = extractMovieFromJson(jsonresponse);

        return movieList;

    }

    @Override
    protected void onPostExecute(List<Movie> movieList) {
        MovieAdapter adapter = new MovieAdapter(movieList);
        recyclerView.setAdapter(adapter);

    }

    private URL createUrl(String stringUrl) {
        URL url = null;

        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            return null;
        }

        return url;

    }

    private String makeHttpRequest(URL url) throws IOException{
        String jsonresponse = null;
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.connect();

            inputStream = urlConnection.getInputStream();
            jsonresponse = readFromStream(inputStream);
        }
        catch (IOException e){

        }
        finally {
            if(urlConnection != null)
                urlConnection.disconnect();
            if (inputStream != null)
                inputStream.close();
        }

        return jsonresponse;

    }

    private String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if(inputStream != null){
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream , Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null){
                output.append(line);
                reader.readLine();
            }
        }
        Log.v("response",output.toString());
        return  output.toString();
    }


    private List<Movie> extractMovieFromJson(String movieJson){

        List<Movie> movieList = new ArrayList<>();
        if (TextUtils.isEmpty(movieJson))
            return  null;

        try{
            JSONObject basejsonresponse = new JSONObject(movieJson);
            JSONObject data = basejsonresponse.getJSONObject("data");

            JSONArray movieArray = data.getJSONArray("movies");

            for (int i = 0; i < movieArray.length(); i++) {

                JSONObject movie = movieArray.getJSONObject(i);
                String movieName = movie.getString("title_long");
                String movieUrl = movie.getString("url");
                String movieImg = movie.getString("background_image_original");

                movieList.add(new Movie(movieName,movieUrl,movieImg));


            }
            return movieList;
        }
        catch (JSONException e){

        }
        return null;
    }
}
}

The JSON Response is not too large.

The following is the JSON Response.

              {  
        "status":"ok",
        "status_message":"Query was successful",
        "data":{  
           "movie_count":6727,
           "limit":1,
           "page_number":1,
           "movies":[  
              {  
                 "id":7078,
                 "url":"https:\/\/yts.am\/movie\/battlecreek-2017",
                 "imdb_code":"tt1880415",
                 "title":"Battlecreek",
                 "title_english":"Battlecreek",
                 "title_long":"Battlecreek (2017)",
                 "slug":"battlecreek-2017",
                 "year":2017,
                 "rating":6.5,
                 "runtime":97,
                 "genres":[  
                    "Drama",
                    "Romance"
                 ],
                 "summary":"Henry is a loner, living with his overprotective mother in a small Southern town called Battlecreek. Henry has a rare sun disease and must avoid sunlight. He lives his life at night -- hanging out at the diner, working the night shift at the gas station and swimming in the creek under the moonlight. Henry doesn't know who he is or what he wants, until he meets Alison. When Alison's car breaks down in Battlecreek, she answers the \"help wanted\" sign at the diner to pay for the repair. Henry is immediately drawn to the mysterious girl. Alison shows Henry that he can live a life he thought impossible, even at the cost of losing his mom and freeing him from his past.",
                 "description_full":"Henry is a loner, living with his overprotective mother in a small Southern town called Battlecreek. Henry has a rare sun disease and must avoid sunlight. He lives his life at night -- hanging out at the diner, working the night shift at the gas station and swimming in the creek under the moonlight. Henry doesn't know who he is or what he wants, until he meets Alison. When Alison's car breaks down in Battlecreek, she answers the \"help wanted\" sign at the diner to pay for the repair. Henry is immediately drawn to the mysterious girl. Alison shows Henry that he can live a life he thought impossible, even at the cost of losing his mom and freeing him from his past.",
                 "synopsis":"Henry is a loner, living with his overprotective mother in a small Southern town called Battlecreek. Henry has a rare sun disease and must avoid sunlight. He lives his life at night -- hanging out at the diner, working the night shift at the gas station and swimming in the creek under the moonlight. Henry doesn't know who he is or what he wants, until he meets Alison. When Alison's car breaks down in Battlecreek, she answers the \"help wanted\" sign at the diner to pay for the repair. Henry is immediately drawn to the mysterious girl. Alison shows Henry that he can live a life he thought impossible, even at the cost of losing his mom and freeing him from his past.",
                 "yt_trailer_code":"rMSP6i7KrHE",
                 "language":"English",
                 "mpa_rating":"R",
                 "background_image":"https:\/\/yts.am\/assets\/images\/movies\/battlecreek_2017\/background.jpg",
                 "background_image_original":"https:\/\/yts.am\/assets\/images\/movies\/battlecreek_2017\/background.jpg",
                 "small_cover_image":"https:\/\/yts.am\/assets\/images\/movies\/battlecreek_2017\/small-cover.jpg",
                 "medium_cover_image":"https:\/\/yts.am\/assets\/images\/movies\/battlecreek_2017\/medium-cover.jpg",
                 "large_cover_image":"https:\/\/yts.am\/assets\/images\/movies\/battlecreek_2017\/large-cover.jpg",
                 "state":"ok",
                 "torrents":[  
                    {  
                       "url":"https:\/\/yts.am\/torrent\/download\/72CEC05285BF162BCD6AFD4566A6DF81DA7AA39F",
                       "hash":"72CEC05285BF162BCD6AFD4566A6DF81DA7AA39F",
                       "quality":"720p",
                       "seeds":0,
                       "peers":0,
                       "size":"727.84 MB",
                       "size_bytes":763195556,
                       "date_uploaded":"2018-02-11 18:10:39",
                       "date_uploaded_unix":1518390639
                    },
                    {  
                       "url":"https:\/\/yts.am\/torrent\/download\/AD72D4BF14B9D4DDC8EC446016C6010473CED78B",
                       "hash":"AD72D4BF14B9D4DDC8EC446016C6010473CED78B",
                       "quality":"1080p",
                       "seeds":0,
                       "peers":0,
                       "size":"1.51 GB",
                       "size_bytes":1621350154,
                       "date_uploaded":"2018-02-11 20:29:05",
                       "date_uploaded_unix":1518398945
                    }
                 ],
                 "date_uploaded":"2018-02-11 18:10:39",
                 "date_uploaded_unix":1518390639
              }
           ]
        },
        "@meta":{  
           "server_time":1518444748,
           "server_timezone":"EST5EDT",
           "api_version":2,
           "execution_time":"0 ms"
        }
     }

I don't understand why this is happening. I've seen some posts mentioning to use GSON. but I think this is not a large response. Please help me.

1

There are 1 best solutions below

0
On BEST ANSWER

You have infinite cycle because you never update your line variable. Try this:

while (line != null) {
    output.append(line);
    line = reader.readLine();
}