java - 尝试在空对象引用上调用虚拟方法 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)'

标签 java android android-studio

使用应用程序搜索姓名时发生错误,因此在应用程序内搜索姓名时未显示任何结果。

尝试在 JSONArray 和 JSONObject 之间进行更改,但出现类似的错误。 URL 正确并且确实以 JSON 格式显示数据。

package com.rjassi.service;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

public class CharacterSearchService extends AbstractService {

    private String query;
    private JSONObject results;
    private JSONObject jsonObject;

    public CharacterSearchService(String query) {
        try {
            this.query = URLEncoder.encode(query, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }

    public JSONObject getResults() {
        return results;
    }

    //This method will run on a separate thread to the UI
    @Override
    public void run() {
        URL url;
        boolean error = false;
        HttpsURLConnection httpsURLConnection = null;
        StringBuilder result = new StringBuilder();

        try {
            url = new URL("https://www.moogleapi.com/api/v1/characters/search?name=" + query);
            httpsURLConnection = (HttpsURLConnection) url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }

            //put the result string into a JSONObject
            JSONArray jsonArray = jsonObject.getJSONArray("name");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) {
                    error = true;

                } else {
                    results = jsonObject;
                }
            }

            /*
            If the JSONObject has a "Response" attribute and it equals false then
            no results were found

            if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) {
                error = true;
            } else {
                results = jsonObject.getJSONArray("Search");
            }
            */
        } catch (Exception ex) {
            ex.printStackTrace();
            results = null;
            error = true;
        } finally {
            if (httpsURLConnection != null) {
                httpsURLConnection.disconnect();
            }
        }

        /*
        Call the serviceCallComplete() method in the super class; AbstractService which
        will then inform the listeners that the search is complete
        */
        super.serviceCallComplete(error);
    }
}
public void serviceComplete(AbstractService abstractService) {

        if (!abstractService.hasError()) {
            //Cast the AbstractService object passed into the method to a CharacterSearchService object
            CharacterSearchService characterSearchService = (CharacterSearchService) abstractService;
            //Create a string array that is the same as the results JSONArray
            String[] result = new String[characterSearchService.getResults().length()];
            //searchResults.clear();

            /*
            Loops through the JSONArray and get the name of each JSONObject it contains.
            Store each name in string array.
            */
            for (int i = 0; i < characterSearchService.getResults().length(); i++) {
                try {
                    //Store each character result as a JSONObject in the ArrayList
                    //searchResults.add(characterSearchService.getResults().getJSONObject(i));
                    android.util.Log.i("sdfsf", characterSearchService.getResults().getJSONObject(String.valueOf(i)).getString("name"));
                    result[i] = characterSearchService.getResults().getJSONObject(String.valueOf(i)).getString("name");
                } catch (JSONException ex) {
                    result[i] = "error";
                }
            }
            //Display the string array on screen in the ListView.
            setListAdapter(new ArrayAdapter<String>(this, R.layout.final_fantasy_list_cell, R.id.text, result));
        }
        else{
            String[] result = new String[]{"No Results"};
            setListAdapter(new ArrayAdapter<String>(this, R.layout.final_fantasy_list_cell, R.id.text, result));
        }
    }

这是搜索名称后发生的错误:

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
        at com.rjassi.service.CharacterSearchService.run(CharacterSearchService.java:53)
        at java.lang.Thread.run(Thread.java:764)

预期输出应显示通过从 API 搜索结果中返回该名称或类似名称来搜索的名称。

最佳答案

jsonObject 从未初始化,因此当您尝试取消引用它时,它会抛出 NullPointerException。使用服务器响应数据初始化 JSONObject。

如果您的响应字符串是格式正确的 JSON,您可以使用以下构造函数初始化 JSONObject: JSON对象 添加到 API 级别 1 公共(public) JSONObject(字符串 json) 使用 JSON 字符串的名称/值映射创建一个新的 JSONObject。

//put the result string into a JSONObject
            JSONArray jsonArray = jsonObject.getJSONArray("name");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.has("Response") && jsonObject.getString("Response").equals("False")) {
                    error = true;

                } else {
                    results = jsonObject;
                }
            }

关于java - 尝试在空对象引用上调用虚拟方法 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58566374/

相关文章:

android - 为什么android创建R.java文件

android - AsyncTask、RejectedExecutionException 和任务限制

java - 相册照片未显示

git - 当我在 Windows 上的 Android Studio 中克隆 git 存储库时,存储库测试失败

java - 如何使用自下而上递归构建 n=3 的情况?

java - 大量表和 Hibernate 内存消耗

java - 如何解释分析结果?

java - 反序列化一个 ArrayList。没有有效的构造函数

java - Android 暂停并完成

android - 打包可穿戴应用