I have a Service that launches an AsyncTask to retrive some data from a device in my homenetwork. When the AsyncTask is done it passes the data read back to the Service using a callback-interface in onPostExecute that the Service implements. The service then reads the information in the passed String and does stuff depending on the information. This works great 9/10 times, but sometimes the String passed from the asynctask is 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);
}
}
Service 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("<dc:creator>");
if (first_index == -1) {
return null;
}
int last_index = mResponse.lastIndexOf("</dc:creator>");
String artist = mResponse.substring(first_index + "<dc:creator>".length(), last_index);
return unEscapeString(artist);
}
To my understanding, the result string is initialized as “No results” and if no result is retrived by the BufferedReader “No Result” is the String that should be passed along. The mConnection is set to 3sec timeout.
I’m really scratching my head over this….
Any ideas?
// Fredrik
The onPostExecute methods gets the values returned from doInBackground as arguments so you should implement those methods differently:
You are overriding the result in every loop step, and you end only up with the last line of the document: