如何在android NullPointerException中解析JSONArray

时间:2015-01-10 15:23:14

标签: android json

我想解析另一个活动传递的jsonObject

intent.putextra("result", json.toString());

它通过名称,分支和会话显示一切正确。但它在获取数组时显示NullPointerException。在这里

            mSubList.add(map);

这个数组有6行。 这是我的代码。请告诉我我错在哪里。

JSONObject json;
ListView sub_list;

private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mSubList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result_page);

    name = (TextView)findViewById(R.id.name_roll);
    branch= (TextView)findViewById(R.id.branchname);
    session = (TextView)findViewById(R.id.Session);

    sub_list = (ListView)findViewById(R.id.sub_list);



    try {
         json = new JSONObject(getIntent().getStringExtra("result"));

        name.setText(json.getString("REGNO")+" - "+json.getString("STUDENTNAME"));
        branch.setText(json.getString("BRANCHNAME"));
        session.setText(json.getString("SESSIONNAME"));

        mComments = json.getJSONArray("DATA");

        // looping through all subjects according to the json object returned
        for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);

            // gets the content of each tag
            String code = c.getString("CCODE");
            String subject = c.getString("COURSENAME");
            String passfail = c.getString("PASSFAIL");

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            map.put("CCODE", code);
            map.put("COURSENAME", subject);
            map.put("PASSFAIL", passfail);
            // adding HashList to ArrayList
            mSubList.add(map);
        }

                ListAdapter adapter = new SimpleAdapter(this, mSubList,
                R.layout.singlesubject, new String[] { "CCODE", "COURSENAME",
                "PASSFAIL" }, new int[] { R.id.sub_id, R.id.sub_name,R.id.sub_res });

        sub_list.setAdapter(adapter);
    }catch(Exception e){
        e.printStackTrace();
    }
  }
}

如果我想更改每个listitem背景(R.layout.singlesubject),如果&#34; PASSFAIl&#34; = P则为绿色,否则为红色。然后我要做什么改变?

3 个答案:

答案 0 :(得分:2)

mSubList.add(map);

这行代码失败,因为在添加地图之前没有初始化数组

您可以使用...

初始化它
mSubList = new ArrayList<Hashmap<String, String>>();

答案 1 :(得分:1)

在添加项目

之前初始化你的mSubList
mSubList = new ArrayList<HashMap<String, String>>();

答案 2 :(得分:1)

我认为您在向其添加数据之前忘记初始化mSubList

mSubList = new ArrayList<HashMap<String, String>>();