我有一个线程从互联网上获取一些数据。它接近它正确执行并检索数据。但是,如果我调用一个应该返回数据的方法,那么我就会留下空值。从那里我得出结论,线程在finning之前不知何故停止。为什么Android线程在完成执行之前被终止?
下面是代码:
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)){
....
“从这里我得出结论,线程在finning之前就停止了。” - 或者,你有一个例外。 – CommonsWare
您如何检索价值以证明它在完成之前确实停止。 –
不@CommonsWare我真的得出了一个结论,我没有看到异常。 GregGiacovelli如果您可能将您的注意力引向我给出的代码示例,最后您会找到两行,并附上一些解释性评论。 – PovilasID