Search code examples
javaandroidjsonandroid-asynctask

cannot pass the json value to function


I am going to get the JSON from the localhost db. Then, I want to put the json into ArrayList. I want to call the parseJSON function. But the JSON is null. Where I should call the function, thanks so much:))

        @Override
        protected String doInBackground(Void... voids) {
                    try {
                        URL url = new URL(urlWebService);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setRequestMethod("GET");
                        StringBuilder sb = new StringBuilder();
                        InputStream input = con.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
                        String json;
                        while ((json = bufferedReader.readLine()) != null) {
                            sb.append(json + "\n");
                        }
                        parseJSON(json);
                        return sb.toString().trim();
                    } catch (Exception e) {
                        return null;
            }
        }
    }
    GetJSON getJSON = new GetJSON(
    );
    getJSON.execute();
}

private void parseJSON(String json) {
    Gson gson = new Gson();
    Type type = new TypeToken<List<EssayElement>>(){}.getType();
    List<EssayElement> mList = gson.fromJson(json, type);
    for (EssayElement essayElement : mList){
    Log.i("Message: " +
            "", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
    }
}

null object reference with String"json"


Solution

  • I would suggest using a proper http library that handles making requests for you like Volley or Retrofit... JSON and Error handling are also builtin, so AsyncTask can completely be removed for that purpose

    But what you have is fine, only json shouldn't be used after the while loop, it's only the last line of the http response, not the full json (assuming there's multiple lines)

    You should really consider parsing the results in the onPostExecute, and possibly even having the parse method return an actual object, or display to the UI