简体   繁体   English

BufferedReader / AsynchTask- java.lang.NullPointerException:锁== null

[英]BufferedReader / AsynchTask- java.lang.NullPointerException: lock == null

I am working on an Android App and I am stuck on an error. 我正在使用Android应用程序,但遇到错误。 I am attempting to communicate with a server and get a JSON object from that server. 我正在尝试与服务器通信并从该服务器获取JSON对象。 I made a class called ServerCommunication which extends AsynchTask. 我制作了一个名为ServerCommunication的类,该类扩展了AsynchTask。 My server communication class has the standard doInBackground() method. 我的服务器通信类具有标准的doInBackground()方法。 In this method, I try to parse a JSON object from a webpage but an exception is thrown in that method. 在此方法中,我尝试从网页中解析JSON对象,但是该方法中引发了异常。

I should mention im running my server locally on my machine for now. 我应该提到我现在在机器上本地运行服务器。 Therefore, the url im passing my ServerCommunication is: http://127.0.0.1:9000/getVehicle/2942 . 因此,传递我的ServerCommunication的URL是: http://127.0.0.1:9000/getVehicle/2942 : http://127.0.0.1:9000/getVehicle/2942 : http://127.0.0.1:9000/getVehicle/2942 getVehicle/ http://127.0.0.1:9000/getVehicle/2942 This webpage contains plain text of a JSON object. 该网页包含JSON对象的纯文本。 Ill include the JSON object at the bottom. 病在底部包括JSON对象。

The exception is: java.lang.NullPointerException: lock == null . 例外是: java.lang.NullPointerException: lock == null This exception is thrown in the second try-catch. 在第二次try-catch中抛出此异常。

The line that causes this exception is: 导致此异常的行是:

BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);

This is line has an error because my InputStream is is null. 这行有一个错误,因为我的InputStream is为null。 For some reason, this line is throwing an exception which is why is is null. 出于某种原因,这条线抛出一个异常,这就是为什么is空。 Ill include my log output for this at the end of this post 在这篇文章的结尾,我会包括我的日志输出

    HttpResponse httpResponse = httpClient.execute(httpPost);

Here is my ServerCommunication class: 这是我的ServerCommunication类:

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;
    }
}

Here is the JSON Object I am trying to parse: 这是我要解析的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}]}

Log Output 日志输出

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$2.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$1.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

Any suggestions? 有什么建议么?

Here 这里

sb.append(line + "n"); sb.append(line +“ n”); <<<<< <<<<<

You are adding n with each line when reading data from BufferedReader which make invalid json string. BufferedReader读取数据时,每行都添加n ,这会使json字符串无效。

Just read and append data in StringBuilder : 只需在StringBuilder读取并追加数据:

   while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

Also before passing InputStream to InputStreamReader make sure is is not null . 又路过之前InputStreamInputStreamReader确保is不是null

I wrote a helper class for WebService connection. 我为WebService连接编写了一个帮助程序类。 I think you can try with it. 我认为您可以尝试一下。

 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();
    }
}

So I found my problem: 所以我发现了我的问题:

I was running my server locally on my laptop on port 9000. I could access my server on my laptop by using localhost:9000 . 我在端口9000的笔记本电脑上本地运行服务器。我可以使用localhost:9000访问笔记本电脑上的服务器。

I was running my android app on my tablet. 我在平板电脑上运行我的Android应用程序。 Therefore when my tablet tried to access localhost:9000 , my tablet was trying to access its own local host, not my laptop. 因此,当我的平板电脑尝试访问localhost:9000 ,我的平板电脑正在尝试访问自己的本地主机,而不是我的笔记本电脑。

To fix this error, the url I had to pass my tablet was MyLaptopIP:9000 . 要解决此错误,我必须通过平板电脑的网址是MyLaptopIP:9000 I also had to ensure that my laptop and tablet were on the same network. 我还必须确保笔记本电脑和平板电脑位于同一网络上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM