Android nullstring从AsyncTask传递到Service

时间:2011-06-30 06:30:32

标签: android service nullpointerexception android-asynctask

我有一个服务,它启动AsyncTask来从我的家庭网络中的设备中检索一些数据。完成AsyncTask后,它会使用Service实现的onPostExecute中的回调接口将读回的数据传递回Service。然后,该服务读取传递的String中的信息,并根据信息执行操作。这种方法效果很好9/10次,但有时从asynctask传递的String为null。

AsyncTask doInBackground:

private String result = "No results";
@Override
    protected Void doInBackground(Void... params) {
            try {
                    OutputStreamWriter wr = new OutputStreamWriter(mConnection.getOutputStream());
                    wr.write(body);
                    wr.flush();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(mConnection.getInputStream()));
                    String line;
                    while ((line = rd.readLine()) != null) {
                            result = line;
                    }
                    wr.close();
                    rd.close();
            } catch (Exception e) {
                    result = e.getMessage();
            }
            return null;
    }

    protected void onPostExecute(Void result) {
            mListener.onHttpResponse(this.result, REQUEST_CODE);
    }

}

服务onHttpResponse:

@Override
    public void onHttpResponse(String response, int REQUEST_CODE) {
            ResponseEnterpreter mEnterpreter = new ResponseEnterpreter(response);
            switch (REQUEST_CODE) {
               case WidgetConstants.REQUEST_LED_STATE :
                   String artist = mEnterpreter.getArtist();  <--- NullPointerException 

ResponseEnterpreter getArtist:

public class ResponseEnterpreter {
    private String mResponse;


    public ResponseEnterpreter(String mResponse) {
            this.mResponse = mResponse;
    }
        public String getArtist() {
            int first_index = mResponse.lastIndexOf("&lt;dc:creator&gt;");
            if (first_index == -1) {
                    return null;
            }

            int last_index = mResponse.lastIndexOf("&lt;/dc:creator&gt;");
            String artist = mResponse.substring(first_index + "&lt;dc:creator&gt;".length(), last_index);

            return unEscapeString(artist);

    }

根据我的理解,结果字符串初始化为“无结果”,如果BufferedReader没有返回结果,则“无结果”是应该传递的字符串。 mConnection设置为3秒超时。

我真的在摸不着头脑......

有什么想法吗?

// Fredrik

1 个答案:

答案 0 :(得分:0)

onPostExecute方法将doInBackground返回的值作为参数获取,因此您应该以不同方式实现这些方法:

protected String doInBackground(Void... params) {
        try {
                //[..]

        } catch (Exception e) {
                return e.getMessage();
        }
        return result;
}

protected void onPostExecute(String result) {
        mListener.onHttpResponse(result, REQUEST_CODE);
}

您在每个循环步骤中都会覆盖结果,并且最后只得到文档的最后一行:

 while ((line = rd.readLine()) != null) {
     result = line;
 }