【问题标题】:NullPointerException with listview on androidNullPointerException 与 android 上的列表视图
【发布时间】:2015-08-10 07:35:41
【问题描述】:

我想在列表视图中显示这个 json 数据。我遇到了这个问题:

java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference

private String[] arrow() throws JSONException {
        json = new JSONObject();
        JSONArray com= null;
        String[] list = new String[10];
        try {
            com = json.getJSONArray("parameters"); // this have 10 different values
        } catch (JSONException e) {
            e.printStackTrace();
        }
                for (int i = 0; i < 10; i++)
                    try {
                        json = com.getJSONObject(i);
                        String forward= json.getString("forward");
                        String back= json.getString("back");

                        list[i]="Forward: " + forward + "\n" + "Backward: " + back;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
        return list;
    }

我是用 textview 做的,但不能用 listview 做,我得到这个空指针.. 请帮忙。谢谢。

【问题讨论】:

  • 第一个e.printStackTrace() 打印什么吗?

标签: java android android-listview nullpointerexception null-pointer


【解决方案1】:

存在多个问题。第一个问题是您使用了两个 try/catch。如果您在第一个中遇到异常,您仍然会去第二次尝试并尝试运行代码。

json = com.getJSONObject(i);

这条线在第二次尝试捕获。在您的情况下,com 似乎为空,因为第一次尝试/捕获时出现异常。

  try { 
            com = json.getJSONArray("parameters"); // this have 10 different values

            for (int i = 0; i < com.length(); i++) {
                json = com.getJSONObject(i);
                String forward= json.getString("forward");
                String back= json.getString("back");

               list[i]="Forward: " + forward + "\n" + "Backward: " + back;
            }
      } catch (JSONException e) {
          e.printStackTrace();
      } 

【讨论】:

  • 得到这个错误:java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on an null object reference
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
相关资源
最近更新 更多