有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试从外部网页接收JSON字符串时出现安卓 Java NullPointerException

我正在尝试将我的安卓应用程序连接到PHP页面。。 这是AsyncTask类函数:

@Override
    protected String doInBackground(String... params) {
        try {
            accountDetails.add(new BasicNameValuePair("Name",params[0]));

            JSONObject json = jparser.makeHttpRequest("http://site.page.php","POST",accountDetails);

           /*My Problem is here..*/
           String registerReport = json.getString("registerReport");
        } catch (Exception e) { 
            error = e.toString();
        }

        return null;
    }

我的php页面返回以下内容:

{"registerReport":"1"}

然后我得到了这个错误: java。lang.NullPointerException:尝试调用虚拟方法“java”。lang.Stringorg。json。JSONObject。空对象引用上的getString(java.lang.String)


共 (1) 个答案

  1. # 1 楼答案

    你的错误

    java.lang.NullPointerException: Attemp to invoke virtual method 'java.lang.Stringorg.json.JSONObject.getString(java.lang.String)' on a null object reference

    这意味着您正试图对空对象调用getString()方法

    在您的特定情况下,在初始化之后,名为“json”的对象为空:

    JSONObject json = jparser.makeHttpRequest("http://site.page.php","POST",accountDetails);

    要修复此错误,可以在调用getString()方法之前尝试对象是否为null:

    @Override
        protected String doInBackground(String... params) {
            try {
                accountDetails.add(new BasicNameValuePair("Name",params[0]));
    
                JSONObject json = jparser.makeHttpRequest("http://site.page.php","POST",accountDetails);
    
               if (json == null) {
                   return null;
               }
               String registerReport = json.getString("registerReport");
            } catch (Exception e) { 
                error = e.toString();
            }
    
        return null;
    }