【发布时间】:2014-05-28 13:11:37
【问题描述】:
我在 android Java 中遇到了 asynctask 的问题。
这是同样的问题:variable returns null outside asynctask android
我的 asynctask 从 url 获取数据,以获取 google maps 的方向!
这是我调用我的代码的地方,在 onrespondre => myvaraible 中有数据,但在变量之外是 null。
public void onResponse(String status, Document doc, final GoogleDirection gd) {
mMap.addMarker(new MarkerOptions()
.position(
new LatLng(myLocation.getLatitude(), myLocation
.getLongitude()))
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.addMarker(new MarkerOptions().position(Position).icon(
BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
mMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
MyVariable = gd.getTotalDurationValue(doc);
}
这是课程:
private class RequestTask extends AsyncTask<String, Void, Document> {
protected Document doInBackground(String... url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url[0]);
HttpResponse response = httpClient.execute(httpPost,
localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
return builder.parse(in);
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Document doc) {
super.onPostExecute(doc);
if (mDirectionListener != null) {
mDirectionListener.onResponse(getStatus(doc), doc,
GoogleDirection.this);
}
}
private String getStatus(Document doc) {
NodeList nl1 = doc.getElementsByTagName("status");
Node node1 = nl1.item(0);
if (isLogging) {
Log.i("GoogleDirection", "Status : " + node1.getTextContent());
}
return node1.getTextContent();
}
}
【问题讨论】:
-
什么是空?你能说得更具体点吗?
-
例如,我声明一个对象:Integer test;当我影响我的变量测试 getDistanceValue 时,我的变量测试现在有一个数据(假设它是 8)但是如果我不在 asynctask 之外,我的变量测试为空(无数据)
-
你的变量将保持为空,直到你的变量被赋值的线程结束
-
@IllegalArgument 我怎么知道线程需要多长时间才能完成?因为如果我不解决这个问题,我就无法在我的字段变量中获得距离或持续时间。
-
在你的 asynctask 的 onpostexecute 方法中
标签: java android android-asynctask google-maps-api-2