我怎样在一个AsyncTask的添加到这个? [英] How do I add an AsyncTask to this?
本文介绍了我怎样在一个AsyncTask的添加到这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建一个Android应用程序,我是相当新的,一般我有,我用它来调用两个不同的Web服务,如下图所示两种不同的方法来穿线,让我怎么改变这些使用AsyncTask的在后台运行线程?
我的code:
公开名单<串GT; getEvacRouteNames(){
如果(android.os.Build.VERSION.SDK_INT> 9){
。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
StrictMode.setThreadPolicy(政策);
}
在的BufferedReader = NULL;
字符串的页面; 尝试{
HttpClient的客户端=新DefaultHttpClient();
HttpPost要求=新HttpPost();
request.setURI(URI)
//添加参数。该ASMX Web服务需要一个双,但被张贴在一个文本字段中输入字符串
清单<&的NameValuePair GT; nameValPairs =新的ArrayList<&的NameValuePair GT;(0);
request.setEntity(新UrlEn codedFormEntity(nameValPairs)); HTT presponse响应= client.execute(请求);
在=新的BufferedReader
(新的InputStreamReader(response.getEntity()的getContent()));
StringBuffer的SB =新的StringBuffer();
串线=;
串NL = System.getProperty(line.separator);
而((行= in.readLine())!= NULL){
sb.append(行+ NL); }
附寄();
页= sb.toString();
DBF的DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
的DocumentBuilder分贝= dbf.newDocumentBuilder();
文档的文档= db.parse(新的InputSource(新StringReader(页)));
//规范化文件
doc.getDocumentElement()正常化()。
//获取根节点
节点列表节点列表= doc.getElementsByTagName(字符串);
//节点有三个子节点
对于(INT N = 0; N< nodeList.getLength(); N ++){
节点node = nodeList.item(N);
串upperNode = node.getNodeName();
。节点温度= node.getChildNodes()项(N);
如果(upperNode.equals(字符串)){
串routeName = node.getTextContent();
routeNamesList.add(node.getTextContent());
}
} //System.out.println(page);
}赶上(例外五){
E.printStackTrace();
}
最后{
如果(在!= NULL){
尝试{
附寄();
}赶上(IOException异常五){
e.printStackTrace();
}
}
}
返回routeNamesList;
}公共EvacRoute getEvacuationRoute(字符串routeName,经纬度currentLocation,纬度字符串,字符串LON)抛出的URISyntaxException,ClientProtocolException,IOException异常,的ParserConfigurationException,SAXException中{
evacRouteList =新的ArrayList< EvacRoute>();
如果(android.os.Build.VERSION.SDK_INT> 9){
。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
StrictMode.setThreadPolicy(政策);
}
EvacRoute evacRoute =新EvacRoute();
evacRoute.setDestinationName(routeName);
在的BufferedReader = NULL;
字符串的页面;
latslngsList =新的ArrayList<&经纬度GT;();
尝试{ latslngsList.add(currentLocation);
HttpClient的客户端=新DefaultHttpClient();
HttpPost要求=新HttpPost();
request.setURI(URI)
//添加参数。该ASMX Web服务需要一个双,但被张贴在一个文本字段中输入字符串
清单<&的NameValuePair GT; nameValPairs =新的ArrayList<&的NameValuePair GT;(2);
nameValPairs.add(新BasicNameValuePair(ROUTE_NAMErouteName));
nameValPairs.add(新BasicNameValuePair(In_Lat,纬度));
nameValPairs.add(新BasicNameValuePair(In_LonLON));
request.setEntity(新UrlEn codedFormEntity(nameValPairs)); HTT presponse响应= client.execute(请求);
在=新的BufferedReader
(新的InputStreamReader(response.getEntity()的getContent()));
StringBuffer的SB =新的StringBuffer();
串线=;
串NL = System.getProperty(line.separator);
而((行= in.readLine())!= NULL){
sb.append(行+ NL); }
附寄();
页= sb.toString();
DBF的DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
的DocumentBuilder分贝= dbf.newDocumentBuilder();
文档的文档= db.parse(新的InputSource(新StringReader(页)));
//规范化文件
doc.getDocumentElement()正常化()。
//获取根节点
节点列表节点列表= doc.getElementsByTagName(simple_ll_waypoint);
双纬度= 0;
双经度= 0;
//节点有三个子节点
对于(INT N = 0; N< nodeList.getLength(); N ++){
串latString =;
串longString =; 节点node = nodeList.item(N);
串upperNode = node.getNodeName();
StringBuilder的addressStrBlder =新的StringBuilder();
的for(int i = 0; I< node.getChildNodes()的getLength();我++){
节点温度= node.getChildNodes()(i)项。
字符串节点名称= temp.getNodeName();
串的nodeValue = temp.getNodeValue();
如果(temp.getNodeName()。equalsIgnoreCase(纬度)){
latString = temp.getTextContent();
纬度= Double.parseDouble(latString); }否则如果(temp.getNodeName()。equalsIgnoreCase(经度)){
longString = temp.getTextContent();
经度= Double.parseDouble(longString);
经纬度经纬度=新的经纬度(纬度,经度);
latslngsList.add(经纬度);
} }
//Log.e(\"Fuel停止,fuelStop.toString());
} //System.out.println(page);
}赶上(例外五){
E.printStackTrace();
}
最后{
如果(在!= NULL){
尝试{
附寄();
}赶上(IOException异常五){
e.printStackTrace();
}
}
}
evacRoute.setLatLngList(latslngsList);
evacRouteList.add(evacRoute);
返回evacRoute;
}
解决方案
您可以从的AsyncTask
扩展您的类,做这样的:
公共类AsyncCustomTask扩展的AsyncTask<太虚,太虚,列表与LT;弦乐>> { @覆盖
保护列表与LT;弦乐> doInBackground(虚空...... PARAMS){
返回getEvacRouteNames();
} @覆盖
保护无效onPostExecute(列表<串GT;的结果){
//函数结束和价值又回来了。
} }
和调用它:
新AsyncCustomTask()执行();
更新了第二个问题
对于有参数的方法,你可以用你喜欢的类构造器:
公共类AsyncSecondCustomTask扩展的AsyncTask<太虚,太虚,EvacRoute> { 私人最终字符串routeName;
私人最终经纬度currentLocation;
私人最终字符串纬度;
私人最终字符串LON; 公共AsyncSecondCustomTask(字符串routeName,经纬度currentLocation,纬度字符串,字符串LON){
this.routeName = routeName;
this.currentLocation = currentLocation;
this.lat =纬度;
this.lon = LON;
} @覆盖
保护EvacRoute doInBackground(虚空...... PARAMS){
返回getEvacuationRoute(routeName,currentLocation,纬度,经度);
} @覆盖
保护无效onPostExecute(EvacRoute结果){
//函数结束和价值又回来了。
} }
和你可以说它是这样的:
新AsyncSecondCustomTask(,NULL,,).execute();
I am creating a Android app and I am fairly new to threading in general I have two different methods that I use to call two different webservices as shown below, so how do I change these to use the AsyncTask to run on a background thread?
My Code:
public List<String> getEvacRouteNames(){
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
BufferedReader in = null;
String page;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(URI)
//Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(0);
request.setEntity(new UrlEncodedFormEntity(nameValPairs));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(page)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("string");
// the node has three child nodes
for (int n = 0; n < nodeList.getLength(); n++) {
Node node=nodeList.item(n);
String upperNode = node.getNodeName();
Node temp=node.getChildNodes().item(n);
if (upperNode.equals("string")){
String routeName = node.getTextContent();
routeNamesList.add(node.getTextContent());
}
}
//System.out.println(page);
} catch (Exception E) {
E.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return routeNamesList;
}
public EvacRoute getEvacuationRoute(String routeName, LatLng currentLocation, String lat, String lon) throws URISyntaxException, ClientProtocolException, IOException, ParserConfigurationException, SAXException{
evacRouteList = new ArrayList<EvacRoute>();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
EvacRoute evacRoute = new EvacRoute();
evacRoute.setDestinationName(routeName);
BufferedReader in = null;
String page;
latslngsList = new ArrayList<LatLng>();
try {
latslngsList.add(currentLocation);
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(URI)
//Add The parameters. The asmx webservice requires a double but gets posted as a string in a text field
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(2);
nameValPairs.add(new BasicNameValuePair("Route_Name", routeName));
nameValPairs.add(new BasicNameValuePair("In_Lat", lat));
nameValPairs.add(new BasicNameValuePair("In_Lon", lon));
request.setEntity(new UrlEncodedFormEntity(nameValPairs));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(page)));
// normalize the document
doc.getDocumentElement().normalize();
// get the root node
NodeList nodeList = doc.getElementsByTagName("simple_ll_waypoint");
double latitude = 0;
double longitude= 0;
// the node has three child nodes
for (int n = 0; n < nodeList.getLength(); n++) {
String latString = "";
String longString = "";
Node node=nodeList.item(n);
String upperNode = node.getNodeName();
StringBuilder addressStrBlder = new StringBuilder();
for (int i = 0; i < node.getChildNodes().getLength(); i++) {
Node temp=node.getChildNodes().item(i);
String nodeName = temp.getNodeName();
String nodevalue = temp.getNodeValue();
if(temp.getNodeName().equalsIgnoreCase("Lat")){
latString = temp.getTextContent();
latitude = Double.parseDouble(latString);
} else if(temp.getNodeName().equalsIgnoreCase("Lon")){
longString = temp.getTextContent();
longitude = Double.parseDouble(longString);
LatLng latlng = new LatLng(latitude, longitude);
latslngsList.add(latlng);
}
}
//Log.e("Fuel Stop", fuelStop.toString());
}
//System.out.println(page);
} catch (Exception E) {
E.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
evacRoute.setLatLngList(latslngsList);
evacRouteList.add(evacRoute);
return evacRoute;
}
解决方案
You can extend your class from AsyncTask
and do like this:
public class AsyncCustomTask extends AsyncTask<Void, Void, List<String>> {
@Override
protected List<String> doInBackground(Void... params) {
return getEvacRouteNames();
}
@Override
protected void onPostExecute(List<String> result) {
// Function finished and value has returned.
}
}
And to call it:
new AsyncCustomTask().execute();
Updated for second question
For the method that have parameters, you can use constructor of your class like:
public class AsyncSecondCustomTask extends AsyncTask<Void, Void, EvacRoute> {
private final String routeName;
private final LatLng currentLocation;
private final String lat;
private final String lon;
public AsyncSecondCustomTask(String routeName, LatLng currentLocation, String lat, String lon) {
this.routeName = routeName;
this.currentLocation = currentLocation;
this.lat = lat;
this.lon = lon;
}
@Override
protected EvacRoute doInBackground(Void... params) {
return getEvacuationRoute(routeName, currentLocation, lat, lon);
}
@Override
protected void onPostExecute(EvacRoute result) {
// Function finished and value has returned.
}
}
And you can call it like:
new AsyncSecondCustomTask("", null, "", "").execute();
这篇关于我怎样在一个AsyncTask的添加到这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文