java - 创建 JSONArray 时出现 NullPointerException

标签 java android json

我正在我的应用程序中使用 Volley 调用 API。将 String 响应转换为 JSONArray 的调用失败,并显示 java.lang.NullPointerException

我不明白为什么会出现NullPointerException。我验证了我正在从 API 获得响应,因此我不应该将空字符串传递给 JSONArray 构造函数。这是代码 fragment 。异常发生在try-catch block 中。

String requestUrl = "https://api.trello.com/1/members/me/boards?key="+keys.apiKeyTrello+"&token="+savedToken;

StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        boardListView.setText("Response is: " + response);
        copyResponse = new String(response);
        Log.d("timer", "reached here");
    }
},
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            copyResponse = new String("[{\"error\":\"error\"}]");
            boardListView.setText("That didn't work!");
    }
});

queue.add(stringRequest);

try {
    JSONArray jsonArray = new JSONArray(copyResponse); // NullPointerException here
}
catch (JSONException e){
    //Handle exception
}

来自 API 的示例响应如下:http://pastebin.com/Bs2GYPcC

堆栈跟踪如下所示:

10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime: FATAL EXCEPTION: main
10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime: Process: im.chaitanya.pomodorotimer, PID: 3535
10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{im.chaitanya.pomodorotimer/im.chaitanya.pomodorotimer.ShowBoardList}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
10-09 19:28:03.856 3535-3535/im.chaitanya.pomodorotimer E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2314)

最佳答案

字符串请求是异步执行的,因此当您调用 try - catch 中的方法时,变量尚未初始化,并且会失败并出现 NullPointerException

我建议您将 try catch 中的代码移至 onSuccess()onErrorResponse 方法。这样在收到服务器的响应后就会调用它。

关于java - 创建 JSONArray 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040295/

相关文章:

java - 如何使用泛型实现类型安全?

Android:复制/复制 SharedPreferences

java - 使用监听器的正确方法是什么?

安卓 4.3 PBO 不工作

javascript - 如何使用 JQuery 将 javascript 对象(从 json webmethod 转换)映射到数组,其中 js 对象仅具有 1 个属性和多个值

javascript - 从现有的 json 创建动态 json

java - Apache POI 是否支持对单词进行两次签名?

java - native 脚本 : Adding native android project to nativescript

Java反序列化json实现抽象对象开闭原则

java - 加载 jasperreports 的 .jrxml 文件