尝试在 Android JSON 中的空对象引用上调用虚拟方法“int java.lang.String.length()”

Posted

技术标签:

【中文标题】尝试在 Android JSON 中的空对象引用上调用虚拟方法“int java.lang.String.length()”【英文标题】:Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference in Android JSON 【发布时间】:2019-06-25 01:57:44 【问题描述】:

我正在运行我的应用程序,但它在 doInBackground() 方法中出现错误。 错误尝试在空对象引用上调用虚拟方法“int java.lang.String.length()”。这是我的代码

Override
    protected Void doInBackground(Void... arg0) 
        // Creating service handler class instance

        ServiceHandler sh = new ServiceHandler();
        // Making a request to url and getting response
        String json_curny_rates = sh.makeServiceCall(url_currency_rates, ServiceHandler.GET);
        String json_curncy_names = sh.makeServiceCall(ulr_curency_namees, ServiceHandler.GET);


        try
        // instantiate our json parser

            jsonObj_rates = new JSONObject(json_curny_rates);

            jsonObj_names = new JSONObject(json_curncy_names);

            s_rtes = jsonObj_rates.getJSONObject("quotes").toString();
            Log.d("s_rates ",""+s_rtes);
            s_names= jsonObj_names.getJSONObject("currencies").toString();
        catch (JSONException e)
        
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        

        return null;
    

    @Override
    protected void onPostExecute(Void result) 
        super.onPostExecute(result);

        add_currency_rates();
        add_country_names();

    


我看过这个平台上的其他帖子,但似乎没有找到我的确切需求。

【问题讨论】:

【参考方案1】:

您的错误显示了您的字符串之一具有空对象引用的完美消息。 这意味着您的某些 JSON 不包含您提到的字符串。

检查您定义的 JSON 密钥是否在您的 JSON 中。

【讨论】:

以上是关于尝试在 Android JSON 中的空对象引用上调用虚拟方法“int java.lang.String.length()”的主要内容,如果未能解决你的问题,请参考以下文章