执行JSONArray JSONObject后调试停止,无法执行for循环吗?

时间:2018-12-15 05:08:58

标签: android arrays json for-loop debugging

我是刚打电话给api的人,我刚刚尝试了一个使用api的{​​{1}}呼叫的简单示例并将其放入http,但是它显示了ListView,我调试代码并在达到NULLPointerExecption对象创建后停止调试?为什么这样我真的不知道,我还尝试在JSONArray文件中将Shinking选项设置为true / false,但是什么也没有发生...

我仅将我的整个项目包含在一个gradle中。这是代码...

mainactivity

1 个答案:

答案 0 :(得分:0)

只需按照下面的

修改您的asynctask
   @Override
    protected ArrayList<User> doInBackground(String[] params) {

        try {
            URL url = new URL("https://api.myjson.com/bins/1422e4");

            HttpURLConnection hc = (HttpURLConnection) url.openConnection();
            InputStream is = hc.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            while (line != null) {
                line = br.readLine();
                data = data + line;
            }

        /*      JSONArray ja = new JSONArray(data);

          for (int i = 0; i < ja.length(); i++) {
                JSONObject jo = (JSONObject) ja.get(i);

                singleParsed = "\n" + "\n" + "NAME : " + jo.get("name") + "\n" +
                        "PASSWORD : " + jo.get("password") + "\n" +
                        "CONTACT : " + jo.get("contact") + "\n" +
                        "COUNTRY : " + jo.get("country") + "\n";

                dataParsed = dataParsed + singleParsed + "\n";
            }*/

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return ParseMoviesJsonString(data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    private ArrayList<User> ParseMoviesJsonString(String dataParsed) throws JSONException {

        final String json_name = "name";
        final String json_password = "password";
        final String json_contact = "contact";
        final String json_country = "country";

        ArrayList<User> list = new ArrayList<>();

        JSONArray MovieArray = new JSONArray(dataParsed);

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

            JSONObject result_movie = MovieArray.getJSONObject(i);
            User movie = new User();
            movie.setU_name(result_movie.getString(json_name));
            movie.setU_password(result_movie.getString(json_password));
            movie.setU_contact(result_movie.getString(json_contact));
            movie.setU_country(result_movie.getString(json_country));

            list.add(movie);
        }
        return list;
    }

根据上述解决方案,您必须在doinbackground中注释该代码,并且还必须进行某些更改(如解析)。您也可以尝试使用GSON库,这是更好的方法。