JSONObject创建抛出空指针异常

时间:2016-08-17 19:20:18

标签: java android json nullpointerexception

我在Android Studio中,我正在尝试创建一个可以进行网络连接的Android应用。我可以获得一些JSON数据,但每当我将我得到的字符串转换为JSONObject时,都会抛出NullPointerException。这是我的日志错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
 at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
 at org.json.JSONTokener.nextValue(JSONTokener.java:94)
 at org.json.JSONObject.<init>(JSONObject.java:156)
 at org.json.JSONObject.<init>(JSONObject.java:173)
 at com.daita.getdusa.GetDataTask.doInBackground(GetDataTask.java:58)
 at com.daita.getdusa.GetDataTask.doInBackground(GetDataTask.java:21)
 at android.os.AsyncTask$2.call(AsyncTask.java:295)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
 at java.lang.Thread.run(Thread.java:818) 

导致异常的代码行是:

JSONObject object = new JSONObject(result);

修改

我被要求添加更多源代码,所以这里是(The AsyncTask)

public class GetDataTask extends AsyncTask<Void, Void, String> {
TextView submitView;
public GetDataTask(TextView submitView){
    this.submitView = submitView;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
    submitView.setText("Loading...");
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    submitView.setText(s);

}

@Override
protected String doInBackground(Void... voids) {
    String result;
    result = getJSON("http://api.datausa.io/attrs/geo/");
    JSONArray data;
    List<String> parsedData = null;
    List<String> geoID = new ArrayList<>();
    try {
        JSONObject jsonObject = new JSONObject(result);
        data = jsonObject.getJSONArray("data");
        parsedData = new ArrayList<>();
        Log.i("DUSA", String.valueOf(jsonObject.length()));
        for(int i=0; i < data.length(); i++){
            parsedData.add(data.getString(i));
        }
        for(String string: parsedData){
            //8, 9
            String[] dta = string.split(",");
            String populationResult = getJSON("http://api.datausa.io/api/?show=geo&sumlevel=all&required=pop&year=latest&geo="+dta[9].substring(1, dta[9].length()-1));
            if (result != null && result != "{\"error\": \"No tables can match the specified query.\"}") {
                JSONObject popObject = new JSONObject(populationResult);
                JSONArray popData = popObject.getJSONArray("data");
                String section = popData.getString(0);
                geoID.add(dta[8] + "," + dta[9] + "," + section);
            } else{
                geoID.add(dta[8] + "," + dta[9] + ", null");
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return geoID.toString();
}

public String getJSON(String url) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.connect();
        int status = c.getResponseCode();
        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (Exception ex) {
        return ex.toString();
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {

            }
        }
    }
    return null;
}
}

注意:如果您想要实时更新源代码,请查看这些文件https://www.dropbox.com/sh/5852rt2rakk6iii/AAAgjsqOTsFfP1N4kS1KzuTBa?dl=0

2 个答案:

答案 0 :(得分:0)

尝试为你做这一切,但让我一步一步让你更简单:

package com.daita.getdusa;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by User on 8/12/2016.
 */
public class GetDataTask extends AsyncTask<String, Void, Void>{
    // Put in Main never here.
    String result;
    String allValues;
    Context context;
    public GetDataTask(Context mContext){
        this.context = mContext;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ((TextView)((MainActivity)context).findViewById(R.id.resultView)).setText("Loading...");
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        ((TextView)((MainActivity)context).findViewById(R.id.resultView)).setText(result);
    }

    @Override
    protected Void doInBackground(String... strings) {
        HttpURLConnection c = null;
        try {
            URL u = new URL("http://api.datausa.io/attrs/geo/"); // use urls first value
            c = (HttpURLConnection) u.openConnection();
            int status = c.getResponseCode();
            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();
                    result = sb.toString();
                    getValue();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (c != null) {
                try {
                    c.disconnect();
                } catch (Exception ex) {

                }
            }
        }
        return null;
    }

    public void getValue() {
        // FIX IT
        // Parse the JSON properly
    }

}

现在了解json解析,数据量巨大,你需要以较小的格式响应这个巨大的json,甚至崩溃在线json格式化程序。 :)

此代码用于显示所有json。希望这会有所帮助。

答案 1 :(得分:0)

    public class Test {
 static String Json="{'root':{['ratedetails':{['levelOne':{["+ "{'FGROUP':'A','rentalpackage':'2D','NOOFDAYS':'2', 'HOURS':'0', 'PERIODPRICE':'100.00',"+ "'CUSTOMERPERDAY':'50.00', 'DRIVERPERDAY':'50.00' ,'KMALLOWANCE':'2', 'EXTKMALLOWPDAY':'60',"+ "'DRIVERKMCHARGE':'5', 'CUSTOMERKMCHARGE':'3', 'MAXIMUMKMCHARGE':'99999999', 'MAXKMCHRGTYPE':'0'"+",'HIDDEN':'2'},"+ "{'FGROUP':'A','rentalpackage':'2D','NOOFDAYS':'2', 'HOURS':'0', 'PERIODPRICE':'100.00',"+ "'CUSTOMERPERDAY':'50.00', 'DRIVERPERDAY':'50.00','KMALLOWANCE':'2', 'EXTKMALLOWPDAY':'60',"+ "'DRIVERKMCHARGE':'5', 'CUSTOMERKMCHARGE':'3', 'MAXIMUMKMCHARGE':'99999999', 'MAXKMCHRGTYPE':'0'"+",'HIDDEN':'2'}"+ "]}"+ "]}"+ "]}}";
 public static void main(String[] args) {
 //new Test().main();
 String s[]=Json.split(",");
 for(int i=0;i<s.length;i++)
{
 if(true){
 System.out.println(s[i].split(":")[s[i].split(":").length-2].substring(s[i].split(":")[s[i].split(":").length-2].indexOf("'")+1, s[i].split(":")[s[i].split(":").length-2].lastIndexOf("'"))+" "+ s[i].split(":")[s[i].split(":").length-1].substring(s[i].split(":")[s[i].split(":").length-1].indexOf("'")+1, s[i].split(":")[s[i].split(":").length-1].lastIndexOf("'")));
 }
else{
 System.out.println(s[i].split(":")[0].replace("'", "").trim()+" "+s[i].split(":")[1].replace("'", "").trim()); } } // System.out.println(Json.split(",")[5].split(":")[1].replace("'", "")); } }