I have a thread which get some data from Internet. It seams that it is executed correctly and data is retrieved. However if I call a method which should return data it leaves me with null. From that I drew a conclusion that thread is somehow stopped just before finning.
Here is the code:
private class getHash extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String str = null;
try {
// Create a URL for the desired page
URL url = new URL(params[0]);
// Read all the text returned by the server
InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
str = in.readLine();
is.close();
isr.close();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hash = str; //If I set a global variable here it gets passed without a hitch
return str;
}
@Override
protected void onPostExecute(String result) {
hash = result; // If I comment the line above and live this one I left with a null
}
}
EDIT:
As requested adding code where the thread was called:
getHash hashThread = new getHash();
hashThread.execute(new String[] {"http://www.full.path/to/the/file.hash"});
if(hash != null && !hash.equals(localHash)){
....
Whatever launched the AsyncTask
Now in your GetHash class
….
Hopefully that helps. Remember
doInBackground()happens on the AsyncTask thread,onPostExecute()executes on the main Thread. Whatever thread calledexecute()is should also be the main thread. Because of the way the main thread works, you can’t expect theonPostCreate()to occur until whatever callback that it was using to callexecute()in the first place, finishes. So that is why I add the return.