我有一个从 Internet 获取一些数据的线程。它表明它正确执行并检索数据。但是,如果我调用一个应该返回数据的方法,它会给我留下空值。从中我得出一个结论,即线程在鳍成型之前以某种方式停止了。
这是代码:
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
}
}
编辑:根据要求添加调用线程的代码:
getHash hashThread = new getHash();
hashThread.execute(new String[] {"http://www.full.path/to/the/file.hash"});
if(hash != null && !hash.equals(localHash)){
....