gpt4 book ai didi

java - JSONObject 创建抛出空指针异常

转载 作者:太空狗 更新时间:2023-10-29 14:46:58 25 4
gpt4 key购买 nike

我在 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

最佳答案

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

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。希望这会有所帮助。

关于java - JSONObject 创建抛出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com