BufferedReader / AsynchTask- java.lang.NullPointerException: lock == null
BufferedReader / AsynchTask- java.lang.NullPointerException: lock == null
我正在开发 Android 应用程序,但遇到错误。我正在尝试与服务器通信并从该服务器获取 JSON 对象。我制作了一个名为 ServerCommunication 的 class,它扩展了 AsynchTask。我的服务器通信 class 具有标准的 doInBackground() 方法。在此方法中,我尝试从网页解析 JSON 对象,但该方法抛出异常。
我应该提到我现在在我的机器上本地运行我的服务器。因此,传递我的 ServerCommunication 的 url 即时消息是:http://127.0.0.1:9000/getVehicle/2942
。此网页包含 JSON 对象的纯文本。我将在底部包含 JSON 对象。
例外情况是:java.lang.NullPointerException: lock == null
。在第二次 try-catch 中抛出此异常。
导致这个异常的行是:
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
此行有错误,因为我的 InputStream is
为空。出于某种原因,此行抛出异常,这就是 is
为空的原因。我将在本文末尾包括我的日志输出
HttpResponse httpResponse = httpClient.execute(httpPost);
这是我的 ServerCommunication class:
class ServerCommunication extends AsyncTask<String, Integer, JSONObject> {
public ServerResponse delegate = null;
public JSONObject jResult;
// this is called whenever you call puhlishProgress(Integer), for example
// when updating a progressbar when downloading stuff
protected void onProgressUpdate(Integer... progress) {
}
// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(JSONObject result) {
delegate.processFinish(result);
}
@Override
protected JSONObject doInBackground(String... params) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
Log.e("Params 0", params[0]);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
这是我要解析的 JSON 对象:
{"Bus":[{"pkey":604,"vehicle_id":261,"trip_id":945162,"route_id":2942,"stop_id":1847,"latitude":43.26762008666992,"longitude":-79.9635009765625,"speed":3.0,"label":"504","bearing":110.0,"odometer":1329300.0,"timestamp":1420775313},{"pkey":605,"vehicle_id":284,"trip_id":945024,"route_id":2942,"stop_id":1926,"latitude":43.22480010986328,"longitude":-79.7864990234375,"speed":10.0,"label":"703","bearing":296.0,"odometer":9481600.0,"timestamp":1420775308},{"pkey":607,"vehicle_id":388,"trip_id":944939,"route_id":2942,"stop_id":1368,"latitude":43.247520446777344,"longitude":-79.84809875488281,"speed":12.0,"label":"1008","bearing":288.0,"odometer":2.21116E+7,"timestamp":1420775317},{"pkey":610,"vehicle_id":422,"trip_id":945158,"route_id":2942,"stop_id":2145,"latitude":43.2575798034668,"longitude":-79.92250061035156,"speed":0.0,"label":"1205","bearing":98.0,"odometer":203000.0,"timestamp":1420775296},{"pkey":623,"vehicle_id":402,"trip_id":945023,"route_id":2942,"stop_id":1955,"latitude":43.25736999511719,"longitude":-79.87146759033203,"speed":8.0,"label":"1102","bearing":286.0,"odometer":5067800.0,"timestamp":1420775311},{"pkey":630,"vehicle_id":276,"trip_id":945154,"route_id":2942,"stop_id":3089,"latitude":43.25257110595703,"longitude":-79.85984802246094,"speed":4.0,"label":"518","bearing":184.0,"odometer":5778500.0,"timestamp":1420775286},{"pkey":634,"vehicle_id":294,"trip_id":945161,"route_id":2942,"stop_id":1923,"latitude":43.23030090332031,"longitude":-79.79962158203125,"speed":13.0,"label":"713","bearing":110.0,"odometer":1.7729E+7,"timestamp":1420775313},{"pkey":639,"vehicle_id":335,"trip_id":944997,"route_id":2942,"stop_id":1320,"latitude":43.257320404052734,"longitude":-79.93509674072266,"speed":2.0,"label":"819","bearing":272.0,"odometer":4.09802E+7,"timestamp":1420775293},{"pkey":653,"vehicle_id":425,"trip_id":944985,"route_id":2942,"stop_id":2560,"latitude":43.23651885986328,"longitude":-79.97097778320312,"speed":13.0,"label":"1208","bearing":210.0,"odometer":5824800.0,"timestamp":1420775288},{"pkey":660,"vehicle_id":317,"trip_id":945168,"route_id":2942,"stop_id":2530,"latitude":43.20967102050781,"longitude":-79.78714752197266,"speed":0.0,"label":"801","bearing":272.0,"odometer":428900.0,"timestamp":1420775282}]}
日志输出
01-09 00:05:29.053: W/System.err(21902): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1:9000 refused
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:235)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1227)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:677)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:567)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:491)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:469)
01-09 00:05:29.053: W/System.err(21902): at com.example.myshuttle.ServerCommunication.doInBackground(ServerCommunication.java:46)
01-09 00:05:29.053: W/System.err(21902): at com.example.myshuttle.ServerCommunication.doInBackground(ServerCommunication.java:1)
01-09 00:05:29.053: W/System.err(21902): at android.os.AsyncTask.call(AsyncTask.java:288)
01-09 00:05:29.053: W/System.err(21902): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-09 00:05:29.053: W/System.err(21902): at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
01-09 00:05:29.053: W/System.err(21902): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-09 00:05:29.053: W/System.err(21902): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-09 00:05:29.053: W/System.err(21902): at java.lang.Thread.run(Thread.java:841)
01-09 00:05:29.053: W/System.err(21902): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 9000): connect failed: ECONNREFUSED (Connection refused)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.IoBridge.connect(IoBridge.java:114)
01-09 00:05:29.053: W/System.err(21902): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-09 00:05:29.053: W/System.err(21902): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
01-09 00:05:29.053: W/System.err(21902): at java.net.Socket.connect(Socket.java:833)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:188)
01-09 00:05:29.053: W/System.err(21902): ... 15 more
01-09 00:05:29.053: W/System.err(21902): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.Posix.connect(Native Method)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.IoBridge.connect(IoBridge.java:112)
01-09 00:05:29.053: W/System.err(21902): ... 20 more
有什么建议吗?
这里
sb.append(line + "n"); <<<<<
您在从 BufferedReader
读取数据时在每一行中添加 n
,这会使 json 字符串无效。
只需读取并追加数据 StringBuilder
:
while ((line = reader.readLine()) != null) {
sb.append(line);
}
另外,在将 InputStream
传递给 InputStreamReader
之前,请确保 is
不是 null
。
我为 WebService 连接编写了一个帮助程序 class。我觉得你可以试试。
public class ServiceHelper {
/**
* Get conten from url
*
* @param url
* @return
*/
public static String getHttp(String url) {
// Get the HTML response
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(request);
return parseStringFromResponse(response);
} catch (Exception e) {
}
return "";
}
/**
* Post content to url
*
* @param url
* @param params
* @return
*/
public static String postHttp(String url, List<NameValuePair> params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add params if need
if (params != null && !params.isEmpty()) {
httppost.setEntity(new UrlEncodedFormEntity(params));
}
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return parseStringFromResponse(response);
} catch (Exception e) {
}
return "";
}
/**
* Parse string from {@link HttpResponse}
*
* @param response
* @return
* @throws Exception
*/
public static final String parseStringFromResponse(
final HttpResponse response) throws Exception {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
return str.toString();
}
}
所以我发现了我的问题:
我是 运行 我的本地服务器,在我的笔记本电脑上的端口 9000 上。我可以使用 localhost:9000
在我的笔记本电脑上访问我的服务器。
我在平板电脑上 运行 我的 android 应用程序。因此,当我的平板电脑尝试访问 localhost:9000
时,我的平板电脑正在尝试访问它自己的本地主机,而不是我的笔记本电脑。
要修复此错误,我必须通过平板电脑的 url 是 MyLaptopIP:9000
。我还必须确保我的笔记本电脑和平板电脑在同一个网络上。
我正在开发 Android 应用程序,但遇到错误。我正在尝试与服务器通信并从该服务器获取 JSON 对象。我制作了一个名为 ServerCommunication 的 class,它扩展了 AsynchTask。我的服务器通信 class 具有标准的 doInBackground() 方法。在此方法中,我尝试从网页解析 JSON 对象,但该方法抛出异常。
我应该提到我现在在我的机器上本地运行我的服务器。因此,传递我的 ServerCommunication 的 url 即时消息是:http://127.0.0.1:9000/getVehicle/2942
。此网页包含 JSON 对象的纯文本。我将在底部包含 JSON 对象。
例外情况是:java.lang.NullPointerException: lock == null
。在第二次 try-catch 中抛出此异常。
导致这个异常的行是:
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
此行有错误,因为我的 InputStream is
为空。出于某种原因,此行抛出异常,这就是 is
为空的原因。我将在本文末尾包括我的日志输出
HttpResponse httpResponse = httpClient.execute(httpPost);
这是我的 ServerCommunication class:
class ServerCommunication extends AsyncTask<String, Integer, JSONObject> {
public ServerResponse delegate = null;
public JSONObject jResult;
// this is called whenever you call puhlishProgress(Integer), for example
// when updating a progressbar when downloading stuff
protected void onProgressUpdate(Integer... progress) {
}
// the onPostexecute method receives the return type of doInBackGround()
protected void onPostExecute(JSONObject result) {
delegate.processFinish(result);
}
@Override
protected JSONObject doInBackground(String... params) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
Log.e("Params 0", params[0]);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
这是我要解析的 JSON 对象:
{"Bus":[{"pkey":604,"vehicle_id":261,"trip_id":945162,"route_id":2942,"stop_id":1847,"latitude":43.26762008666992,"longitude":-79.9635009765625,"speed":3.0,"label":"504","bearing":110.0,"odometer":1329300.0,"timestamp":1420775313},{"pkey":605,"vehicle_id":284,"trip_id":945024,"route_id":2942,"stop_id":1926,"latitude":43.22480010986328,"longitude":-79.7864990234375,"speed":10.0,"label":"703","bearing":296.0,"odometer":9481600.0,"timestamp":1420775308},{"pkey":607,"vehicle_id":388,"trip_id":944939,"route_id":2942,"stop_id":1368,"latitude":43.247520446777344,"longitude":-79.84809875488281,"speed":12.0,"label":"1008","bearing":288.0,"odometer":2.21116E+7,"timestamp":1420775317},{"pkey":610,"vehicle_id":422,"trip_id":945158,"route_id":2942,"stop_id":2145,"latitude":43.2575798034668,"longitude":-79.92250061035156,"speed":0.0,"label":"1205","bearing":98.0,"odometer":203000.0,"timestamp":1420775296},{"pkey":623,"vehicle_id":402,"trip_id":945023,"route_id":2942,"stop_id":1955,"latitude":43.25736999511719,"longitude":-79.87146759033203,"speed":8.0,"label":"1102","bearing":286.0,"odometer":5067800.0,"timestamp":1420775311},{"pkey":630,"vehicle_id":276,"trip_id":945154,"route_id":2942,"stop_id":3089,"latitude":43.25257110595703,"longitude":-79.85984802246094,"speed":4.0,"label":"518","bearing":184.0,"odometer":5778500.0,"timestamp":1420775286},{"pkey":634,"vehicle_id":294,"trip_id":945161,"route_id":2942,"stop_id":1923,"latitude":43.23030090332031,"longitude":-79.79962158203125,"speed":13.0,"label":"713","bearing":110.0,"odometer":1.7729E+7,"timestamp":1420775313},{"pkey":639,"vehicle_id":335,"trip_id":944997,"route_id":2942,"stop_id":1320,"latitude":43.257320404052734,"longitude":-79.93509674072266,"speed":2.0,"label":"819","bearing":272.0,"odometer":4.09802E+7,"timestamp":1420775293},{"pkey":653,"vehicle_id":425,"trip_id":944985,"route_id":2942,"stop_id":2560,"latitude":43.23651885986328,"longitude":-79.97097778320312,"speed":13.0,"label":"1208","bearing":210.0,"odometer":5824800.0,"timestamp":1420775288},{"pkey":660,"vehicle_id":317,"trip_id":945168,"route_id":2942,"stop_id":2530,"latitude":43.20967102050781,"longitude":-79.78714752197266,"speed":0.0,"label":"801","bearing":272.0,"odometer":428900.0,"timestamp":1420775282}]}
日志输出
01-09 00:05:29.053: W/System.err(21902): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1:9000 refused
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:235)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1227)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:677)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:567)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:491)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:469)
01-09 00:05:29.053: W/System.err(21902): at com.example.myshuttle.ServerCommunication.doInBackground(ServerCommunication.java:46)
01-09 00:05:29.053: W/System.err(21902): at com.example.myshuttle.ServerCommunication.doInBackground(ServerCommunication.java:1)
01-09 00:05:29.053: W/System.err(21902): at android.os.AsyncTask.call(AsyncTask.java:288)
01-09 00:05:29.053: W/System.err(21902): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-09 00:05:29.053: W/System.err(21902): at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
01-09 00:05:29.053: W/System.err(21902): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
01-09 00:05:29.053: W/System.err(21902): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
01-09 00:05:29.053: W/System.err(21902): at java.lang.Thread.run(Thread.java:841)
01-09 00:05:29.053: W/System.err(21902): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 9000): connect failed: ECONNREFUSED (Connection refused)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.IoBridge.connect(IoBridge.java:114)
01-09 00:05:29.053: W/System.err(21902): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-09 00:05:29.053: W/System.err(21902): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
01-09 00:05:29.053: W/System.err(21902): at java.net.Socket.connect(Socket.java:833)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-09 00:05:29.053: W/System.err(21902): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:188)
01-09 00:05:29.053: W/System.err(21902): ... 15 more
01-09 00:05:29.053: W/System.err(21902): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.Posix.connect(Native Method)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-09 00:05:29.053: W/System.err(21902): at libcore.io.IoBridge.connect(IoBridge.java:112)
01-09 00:05:29.053: W/System.err(21902): ... 20 more
有什么建议吗?
这里
sb.append(line + "n"); <<<<<
您在从 BufferedReader
读取数据时在每一行中添加 n
,这会使 json 字符串无效。
只需读取并追加数据 StringBuilder
:
while ((line = reader.readLine()) != null) {
sb.append(line);
}
另外,在将 InputStream
传递给 InputStreamReader
之前,请确保 is
不是 null
。
我为 WebService 连接编写了一个帮助程序 class。我觉得你可以试试。
public class ServiceHelper {
/**
* Get conten from url
*
* @param url
* @return
*/
public static String getHttp(String url) {
// Get the HTML response
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(request);
return parseStringFromResponse(response);
} catch (Exception e) {
}
return "";
}
/**
* Post content to url
*
* @param url
* @param params
* @return
*/
public static String postHttp(String url, List<NameValuePair> params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add params if need
if (params != null && !params.isEmpty()) {
httppost.setEntity(new UrlEncodedFormEntity(params));
}
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return parseStringFromResponse(response);
} catch (Exception e) {
}
return "";
}
/**
* Parse string from {@link HttpResponse}
*
* @param response
* @return
* @throws Exception
*/
public static final String parseStringFromResponse(
final HttpResponse response) throws Exception {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
return str.toString();
}
}
所以我发现了我的问题:
我是 运行 我的本地服务器,在我的笔记本电脑上的端口 9000 上。我可以使用 localhost:9000
在我的笔记本电脑上访问我的服务器。
我在平板电脑上 运行 我的 android 应用程序。因此,当我的平板电脑尝试访问 localhost:9000
时,我的平板电脑正在尝试访问它自己的本地主机,而不是我的笔记本电脑。
要修复此错误,我必须通过平板电脑的 url 是 MyLaptopIP:9000
。我还必须确保我的笔记本电脑和平板电脑在同一个网络上。