如何从AsyncTask的返回一个对象主类的android [英] How to return an object from the asynctask to the main class in android

查看:185
本文介绍了如何从AsyncTask的返回一个对象主类的android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的文档返回给我的主类,但即使使用全局变量忽略了最低工作,这是因为AsyncTask的没吃完,我认为是有一个解决方案,以获取对象形式的AsyncTask请工作? 我已经尝试过了做作的onPostExecute但对象得到空,如果我是AsyncTask的外 这是类:

 私有类RequestTask扩展的AsyncTask<字符串,太虚,文件> {
    受保护的文档doInBackground(字符串... URL){
        尝试 {
            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpContext的localContext =新BasicHttpContext();
            HttpPost httpPost =新HttpPost(网址[0]);
            HTT presponse响应= httpClient.execute(httpPost,
                    localContext);
            。InputStream的时间= response.getEntity()的getContent();
            DocumentBuilder的建设者= DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();

            返回builder.parse(在);
        }赶上(IOException异常E){
            e.printStackTrace();
        }赶上(的ParserConfigurationException E){
            e.printStackTrace();
        }赶上(的SAXException E){
            e.printStackTrace();
        }

        返回null;
    }

    保护无效onPostExecute(DOC文件){
        super.onPostExecute(DOC);

        如果(mDirectionListener!= NULL){
            mDirectionListener.onResponse(的getStatus(DOC),DOC,
                    GoogleDirection.this);
        }
    }

    私人的getStatus字符串(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(状态);
        节点节点1 = nl1.item(0);

        如果(isLogging){
            Log.i(GoogleDirection,状态:+ node1.getTextContent());
        }

        返回node1.getTextContent();
    }
}
 

我试过这么多的解决方案,没有人他们的作品......请帮帮我!

更新: 有些错误,我得到:

我的code的结构: ClassMain,类GoogleDirection和内部类是AsyncTask的

这是我的包含一个内部类的第一类(AsyncTask的) 包com.example.busmapsproject.app;

 进口android.annotation.Sup pressLint;
进口android.content.Context;
进口android.os.AsyncTask;
进口android.util.DisplayMetrics;
进口android.util.Log;

进口com.google.android.gms.maps.model.LatLng;
进口com.google.android.gms.maps.model.PolylineOptions;

进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.protocol.BasicHttpContext;
进口org.apache.http.protocol.HttpContext;
进口org.w3c.dom.Document中;
进口org.w3c.dom.Node中;
进口org.w3c.dom.NodeList;
进口org.xml.sax.SAXException;

进口java.io.IOException异常;
进口的java.io.InputStream;
进口的java.util.ArrayList;

进口javax.xml.parsers.DocumentBuilder中;
进口javax.xml.parsers.DocumentBuilderFactory中;
进口javax.xml.parsers.ParserConfigurationException;


@燮pressLint(NewApi)
公共类GoogleDirection {
    公共最后静态字符串MODE_WALKING =行走;
    私人OnDirectionResponseListener mDirectionListener = NULL;
    私人布尔isLogging = FALSE;
    民营背景myContext = NULL;
    私人文档测试;

    公共GoogleDirection(上下文的背景下){
        myContext =背景;
    }

    公共字符串请求(经纬度开始,经纬度结束,字符串模式){
        最终的字符串URL =htt​​p://maps.googleapis.com/maps/api/directions/xml? +
            原产地=+ start.latitude +,+ start.longitude +
            与&目的地=+ end.latitude +,+ end.longitude +
            &放大器;传感器=假放;单位=指标和放大器;模式=+模式;

        如果(isLogging){
            //在logcat的显示信息报告(成功)
            Log.i(GoogleDirection,URL:+网址);
        }

            新RequestTask()执行(URL);


        返回URL;
    }

    公共无效setLogging(布尔州){
        isLogging =状态;
    }

    公众的getStatus字符串(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(状态);
        节点节点1 = nl1.item(0);

        如果(isLogging){
            Log.i(GoogleDirection,状态:+ node1.getTextContent());
        }

        返回node1.getTextContent();
    }

    公众的String [] getDurationText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        的String [] arr_str =新的String [nl1.getLength() -  1];

        的for(int i = 0;我≤(nl1.getLength() -  1);我++){
            节点节点1 = nl1.item(ⅰ);
            节点列表NL2 = node1.getChildNodes(); //返回一个节点的子(持续时间有文字和值)
            节点节点2 = nl2.item(getNodeIndex(NL2,文本));
            arr_str [I] = node2.getTextContent();

            如果(isLogging){
                Log.i(GoogleDirection
                    DurationText:+ node2.getTextContent());
            }
        }

        返回arr_str;
    }

    公众诠释[] getDurationValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        INT [] arr_int =新INT [nl1.getLength() -  1];

        的for(int i = 0;我≤(nl1.getLength() -  1);我++){
            节点节点1 = nl1.item(ⅰ);
            节点列表NL2 = node1.getChildNodes();
            节点节点2 = nl2.item(getNodeIndex(NL2,值));
            arr_int [I] =的Integer.parseInt(node2.getTextContent());

            如果(isLogging){
                Log.i(GoogleDirection,持续时间:+
                    node2.getTextContent());
            }
        }

        返回arr_int;
    }

    公共字符串getTotalDurationText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        节点节点1 = nl1.item(nl1.getLength() -  1);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,文本));

        如果(isLogging){
            Log.i(GoogleDirection,TotalDuration:+
                node2.getTextContent());
        }

        返回node2.getTextContent();
    }

    公众诠释getTotalDurationValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(期限);
        节点节点1 = nl1.item(nl1.getLength() -  1);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,值));

        如果(isLogging){
            Log.i(GoogleDirection,TotalDuration:+
                node2.getTextContent());
        }
        返回的Integer.parseInt(node2.getTextContent());
    }

    公众的String [] getDistanceText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        的String [] arr_str =新的String [nl1.getLength() -  1];

        的for(int i = 0;我≤(nl1.getLength() -  1);我++){
            节点节点1 = nl1.item(ⅰ);
            节点列表NL2 = node1.getChildNodes();
            节点节点2 = nl2.item(getNodeIndex(NL2,文本));
            arr_str [I] = node2.getTextContent();

            如果(isLogging){
                Log.i(GoogleDirection
                    DurationText:+ node2.getTextContent());
            }
        }

        返回arr_str;
    }

    公众诠释[] getDistanceValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        INT [] arr_int =新INT [nl1.getLength() -  1];

        的for(int i = 0;我≤(nl1.getLength() -  1);我++){
            节点节点1 = nl1.item(ⅰ);
            节点列表NL2 = node1.getChildNodes();
            节点节点2 = nl2.item(getNodeIndex(NL2,值));
            arr_int [I] =的Integer.parseInt(node2.getTextContent());

            如果(isLogging){
                Log.i(GoogleDirection,持续时间:+
                    node2.getTextContent());
            }
        }

        返回arr_int;
    }

    公共字符串getTotalDistanceText(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        节点节点1 = nl1.item(nl1.getLength() -  1);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,文本));

        如果(isLogging){
            Log.i(GoogleDirection,TotalDuration:+
                node2.getTextContent());
        }

        返回node2.getTextContent();
    }

    公众诠释getTotalDistanceValue(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(距离);
        节点节点1 = nl1.item(nl1.getLength() -  1);
        节点列表NL2 = node1.getChildNodes();
        节点节点2 = nl2.item(getNodeIndex(NL2,值));

        如果(isLogging){
            Log.i(GoogleDirection,TotalDuration:+
                node2.getTextContent());
        }

        返回的Integer.parseInt(node2.getTextContent());
    }

    公共字符串getStartAddress(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(START_ADDRESS);
        节点节点1 = nl1.item(0);

        如果(isLogging){
            Log.i(GoogleDirection,StartAddress开始:+
                node1.getTextContent());
        }

        返回node1.getTextContent();
    }

    公共字符串getEndAddress(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(end_address);
        节点节点1 = nl1.item(0);

        如果(isLogging){
            Log.i(GoogleDirection,StartAddress开始:+
                node1.getTextContent());
        }

        返回node1.getTextContent();
    }

    公共字符串getCop​​yRights(DOC文件){
        节点列表NL1 = doc.getElementsByTagName(著作权);
        节点节点1 = nl1.item(0);

        如果(isLogging){
            Log.i(GoogleDirection,著作权:+ node1.getTextContent());
        }

        返回node1.getTextContent();
    }

    公众的ArrayList<经纬度> getDirection(DOC文件){
        节点列表NL1;
        节点列表NL2;
        节点列表NL3;
        ArrayList的<经纬度> listGeopoints =新的ArrayList<经纬度>();
        NL1 = doc.getElementsByTagName(步);

        如果(nl1.getLength()大于0){
            的for(int i = 0; I< nl1.getLength();我++){
                节点节点1 = nl1.item(ⅰ);
                NL2 = node1.getChildNodes();

                节点locationNode = nl2.item(getNodeIndex(NL2的start_location));
                NL3 = locationNode.getChildNodes();

                节点latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                双纬度= Double.parseDouble(latNode.getTextContent());
                节点lngNode = nl3.item(getNodeIndex(NL3,LNG));
                双LNG = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));

                locationNode = nl2.item(getNodeIndex(NL2,折线));
                NL3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(NL3,分));

                ArrayList的<经纬度> ARR =去$ C $℃聚(latNode.getTextContent());

                对于(INT J = 0; J< arr.size(); J ++){
                    listGeopoints.add(新经纬度(arr.get(J).latitude,
                            arr.get(J).longitude));
                }

                locationNode = nl2.item(getNodeIndex(NL2,END_LOCATION));
                NL3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                纬度= Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(NL3,LNG));
                液化天然气= Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));
            }
        }

        返回listGeopoints;
    }

    公众的ArrayList<经纬度> getSection(DOC文件){
        节点列表NL1;
        节点列表NL2;
        节点列表NL3;
        ArrayList的<经纬度> listGeopoints =新的ArrayList<经纬度>();
        NL1 = doc.getElementsByTagName(步);

        如果(nl1.getLength()大于0){
            的for(int i = 0; I< nl1.getLength();我++){
                节点节点1 = nl1.item(ⅰ);
                NL2 = node1.getChildNodes();

                节点locationNode = nl2.item(getNodeIndex(NL2,END_LOCATION));
                NL3 = locationNode.getChildNodes();

                节点latNode = nl3.item(getNodeIndex(NL3,纬度​​));
                双纬度= Double.parseDouble(latNode.getTextContent());
                节点lngNode = nl3.item(getNodeIndex(NL3,LNG));
                双LNG = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(新经纬度(纬度,经度));
            }
        }

        返回listGeopoints;
    }

    公共PolylineOptions getPolyline(DOC文件,诠释的宽度,诠释颜色){
        ArrayList的<经纬度> arr_pos = getDirection(DOC);
        PolylineOptions rectLine =新PolylineOptions()。宽度(dpToPx(宽))
                                                        。颜色(颜色);

        的for(int i = 0; I< arr_pos.size();我++)
            rectLine.add(arr_pos.get(ⅰ));

        返回rectLine;
    }

    私人诠释getNodeIndex(节点列表NL,串节点名称){
        的for(int i = 0; I< nl.getLength();我++){
            如果(nl.item(我).getNodeName()。等于(节点名称)){
                返回我;
            }
        }

        返回-1;
    }

    私人的ArrayList<经纬度>德$ C $℃聚(字符串连接codeD){
        ArrayList的<经纬度>聚=新的ArrayList<经纬度>();
        INT索引= 0;
        INT LEN = EN coded.length();
        INT纬度= 0;
        INT LNG = 0;

        而(指数< LEN){
            INT B:
            INT移位= 0;
            INT结果为0;

            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =((B和0x1F的)LT;<移);
                Shift + = 5;
            }而(B> = 0x20的);

            INT DLAT =(((导致&安培; 1)= 0)(〜(导致>→1)):!?(结果>→1));
            纬度+ = DLAT;
            移= 0;
            结果= 0;

            做 {
                B = EN coded.charAt(指数++) -  63;
                结果| =((B和0x1F的)LT;<移);
                Shift + = 5;
            }而(B> = 0x20的);

            INT dlng =(((导致&安培; 1)= 0)(〜(结果>→1)):!?(导致>→1));
            LNG + = dlng;

            经纬度位置=新的经纬度((双)纬度/ 1E5,(双)LNG / 1E5);
            poly.add(位置);
        }

        返回聚;
    }

    //转换DP像素
    私人诠释dpToPx(INT DP){
        DisplayMetrics displayMetrics = myContext.getResources()
                                                 .getDisplayMetrics();
        INT PX = Math.round(DP *(displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

        返回像素;
    }

    公共无效setOnDirectionResponseListener(
        OnDirectionResponseListener监听器){
        mDirectionListener =侦听器;
    }

    公共接口OnDirectionResponseListener {
        公共无效onResponse(字符串状态,DOC文件,GoogleDirection GD);
    }

    私有类RequestTask扩展的AsyncTask<字符串,太虚,文件> {

        受保护的文档doInBackground(字符串... URL){
            尝试 {
                HttpClient的HttpClient的=新DefaultHttpClient();
                HttpContext的localContext =新BasicHttpContext();
                HttpPost httpPost =新HttpPost(网址[0]);
                HTT presponse响应= httpClient.execute(httpPost,
                        localContext);
                。InputStream的时间= response.getEntity()的getContent();
                DocumentBuilder的建设者= DocumentBuilderFactory.newInstance()
                                                                .newDocumentBuilder();

                返回builder.parse(在);
            }赶上(IOException异常E){
                e.printStackTrace();
            }赶上(的ParserConfigurationException E){
                e.printStackTrace();
            }赶上(的SAXException E){
                e.printStackTrace();
            }

            返回null;
        }

        保护无效onPostExecute(DOC文件){
            super.onPostExecute(DOC);

            如果(mDirectionListener!= NULL){
                mDirectionListener.onResponse(的getStatus(DOC),DOC,
                    GoogleDirection.this);
            }
        }


        私人的getStatus字符串(DOC文件){
            节点列表NL1 = doc.getElementsByTagName(状态);
            节点节点1 = nl1.item(0);

            如果(isLogging){
                Log.i(GoogleDirection,状态:+ node1.getTextContent());
            }

            返回node1.getTextContent();
        }
    }
}
 

这是我的主类:     进口android.graphics.Color;     进口android.os.Bundle;     进口android.support.v4.app.FragmentActivity;

 进口com.google.android.gms.maps.GoogleMap;
进口com.google.android.gms.maps.SupportMapFragment;
进口com.google.android.gms.maps.model.BitmapDesc​​riptorFactory;
进口com.google.android.gms.maps.model.LatLng;
进口com.google.android.gms.maps.model.MarkerOptions;

进口org.w3c.dom.Document中;

公共类MapsActivity扩展FragmentActivity {

    私人GoogleMap的MMAP; //可能为空,如果谷歌Play业务APK不可用。
    私人GoogleDirection GD;
    私人经纬度Arret =新的经纬度(30.413647,-9.555608);
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_maps);
        GD =新GoogleDirection(本);
        setUpMapIfNeeded();
    }

    @覆盖
    保护无效onResume(){
        super.onResume();
        setUpMapIfNeeded();
    }

    / **
     *设定地图,如果有可能的话(即谷歌播放服务APK是正确的
     *安装)和地图尚未实例化的。这将确保我们只有永远
     *电话{@link #setUpMap()}一旦当{@link #mMap}不为空。
     *所述p为H.;
     *如果没有安装{@link SupportMapFragment}(和
     * {@link com.google.android.gms.maps.MapView的MapView})将显示为用户提示
     *安装/更新谷歌播放服务APK他们的设备上。
     *所述p为H.;
     *用户可以按照提示正确后,返回到该FragmentActivity
     *安装/升级/使谷歌Play业务。由于FragmentActivity不得
     *已在此过程中被完全摧毁(很可能只会是
     *停止或暂停),{@link #onCreate(包)}可能不会被再次调用,所以我们应该把这种
     *在方法{@link #onResume()},以保证它会被调用。
     * /
    私人无效setUpMapIfNeeded(){
        //做一个空检查确认,我们还没有实例化的地图。
        如果(MMAP == NULL){
            //尝试获取来自SupportMapFragment地图。
            MMAP =((SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map))
                    .getMap();
            mMap.setMyLocationEnabled(真正的);
            //检查如果我们成功取得地图。
            如果(MMAP!= NULL){
                setUpMap();
            }
        }
    }

    / **
     *这是我们可以添加标记或线条,添加监听器或移动摄像头。在这种情况下,我们
     *只是增加非洲附近的一个标志。
     *所述p为H.;
     *这应该只被调用一次,当我们确信{@link #mMap}不为空。
     * /
    私人无效setUpMap(){

        MyLocation LOC =新MyLocation(本);
        mMap.addMarker(新MarkerOptions()。位置(新的经纬度(loc.getLatitude(),loc.getLongitude()))
                .icon(BitmapDesc​​riptorFactory.defaultMarker(
                        BitmapDesc​​riptorFactory.HUE_BLUE)));
        mMap.addMarker(新MarkerOptions()。位置(Arret)
                .icon(BitmapDesc​​riptorFactory.defaultMarker(
                        BitmapDesc​​riptorFactory.HUE_BLUE)));
        gd.setOnDirectionResponseListener(新GoogleDirection.OnDirectionResponseListener(){
            @覆盖
            公共无效onResponse(字符串状态,DOC文件,GoogleDirection GD){
                mMap.addPolyline(gd.getPolyline(DOC,3,Color.RED));
                gd.getTotalDurationValue(DOC);
            }
        });
        gd.setLogging(真正的);
        //经纬度测试=新的经纬度((loc.getLatitude()+ 0.1F),(loc.getLongitude()+ 0.5F));
        gd.request(新经纬度(loc.getLatitude(),loc.getLongitude()),Arret,GoogleDirection.MODE_WALKING);

    }
}
 

解决方案

使用监听器监听者。例2分钟。

使用类似的接口:

 公共接口OnTaskCompleted {
    无效onTaskCompleted(文献DOC);
}
 

扩展你的活动与该接口:

 公共YourActivity实现OnTaskCompleted {
   //你的活动
}
 

让AsyncTask的发送信息时,它的完成。

 公共YourTask延伸的AsyncTask<对象,对象,对象> {
私人OnTaskCompleted监听;

//你的东西
公共YourTask(OnTaskCompleted监听器){
    this.listener =侦听器;
}

保护无效onPostExecute(对象o){
    listener.onTaskCompleted(DOC);
}
}
 

现在你实现onTaskCompleted在你的活动和处理已经由AsyncTask的给出的文档。

I want to return the document to my main class but even using a global variable dosen't work it's because the asynctask didn't finish the job I think is there a solution to get an object form asynctask please ? I already tried the affectation in the onPostExecute but the object get null if i'm outside the asynctask this is the class :

    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();
    }
}

I tried so much solution and no one of them works ... please help me !

UPDATE : Some errors I get :

The structure of my code : ClassMain , Class GoogleDirection and innerClass is the asynctask

This is my first class that contain an inner class (Asynctask) package com.example.busmapsproject.app;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;

import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


@SuppressLint("NewApi")
public class GoogleDirection {
    public final static String MODE_WALKING = "walking";
    private OnDirectionResponseListener mDirectionListener = null;
    private boolean isLogging = false;
    private Context myContext = null;
    private Document test;

    public GoogleDirection(Context context) {
        myContext = context;
    }

    public String request(LatLng start, LatLng end, String mode) {
        final String url = "http://maps.googleapis.com/maps/api/directions/xml?" +
            "origin=" + start.latitude + "," + start.longitude +
            "&destination=" + end.latitude + "," + end.longitude +
            "&sensor=false&units=metric&mode=" + mode;

        if (isLogging) {
            //Display information in logcat (report success)
            Log.i("GoogleDirection", "URL : " + url);
        }

            new RequestTask().execute(url);


        return url;
    }

    public void setLogging(boolean state) {
        isLogging = state;
    }

    public 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();
    }

    public String[] getDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        String[] arr_str = new String[nl1.getLength() - 1];

        for (int i = 0; i < (nl1.getLength() - 1); i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes(); //Return child of a node (Duration have text and value)
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();

            if (isLogging) {
                Log.i("GoogleDirection",
                    "DurationText : " + node2.getTextContent());
            }
        }

        return arr_str;
    }

    public int[] getDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        int[] arr_int = new int[nl1.getLength() - 1];

        for (int i = 0; i < (nl1.getLength() - 1); i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());

            if (isLogging) {
                Log.i("GoogleDirection", "Duration : " +
                    node2.getTextContent());
            }
        }

        return arr_int;
    }

    public String getTotalDurationText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));

        if (isLogging) {
            Log.i("GoogleDirection", "TotalDuration : " +
                node2.getTextContent());
        }

        return node2.getTextContent();
    }

    public int getTotalDurationValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));

        if (isLogging) {
            Log.i("GoogleDirection", "TotalDuration : " +
                node2.getTextContent());
        }
        return Integer.parseInt(node2.getTextContent());
    }

    public String[] getDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        String[] arr_str = new String[nl1.getLength() - 1];

        for (int i = 0; i < (nl1.getLength() - 1); i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            arr_str[i] = node2.getTextContent();

            if (isLogging) {
                Log.i("GoogleDirection",
                    "DurationText : " + node2.getTextContent());
            }
        }

        return arr_str;
    }

    public int[] getDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        int[] arr_int = new int[nl1.getLength() - 1];

        for (int i = 0; i < (nl1.getLength() - 1); i++) {
            Node node1 = nl1.item(i);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            arr_int[i] = Integer.parseInt(node2.getTextContent());

            if (isLogging) {
                Log.i("GoogleDirection", "Duration : " +
                    node2.getTextContent());
            }
        }

        return arr_int;
    }

    public String getTotalDistanceText(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));

        if (isLogging) {
            Log.i("GoogleDirection", "TotalDuration : " +
                node2.getTextContent());
        }

        return node2.getTextContent();
    }

    public int getTotalDistanceValue(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));

        if (isLogging) {
            Log.i("GoogleDirection", "TotalDuration : " +
                node2.getTextContent());
        }

        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);

        if (isLogging) {
            Log.i("GoogleDirection", "StartAddress : " +
                node1.getTextContent());
        }

        return node1.getTextContent();
    }

    public String getEndAddress(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);

        if (isLogging) {
            Log.i("GoogleDirection", "StartAddress : " +
                node1.getTextContent());
        }

        return node1.getTextContent();
    }

    public String getCopyRights(Document doc) {
        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);

        if (isLogging) {
            Log.i("GoogleDirection", "CopyRights : " + node1.getTextContent());
        }

        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection(Document doc) {
        NodeList nl1;
        NodeList nl2;
        NodeList nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");

        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();

                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));

                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());

                for (int j = 0; j < arr.size(); j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude,
                            arr.get(j).longitude));
                }

                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public ArrayList<LatLng> getSection(Document doc) {
        NodeList nl1;
        NodeList nl2;
        NodeList nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");

        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();

                Node locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();

                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    public PolylineOptions getPolyline(Document doc, int width, int color) {
        ArrayList<LatLng> arr_pos = getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(dpToPx(width))
                                                        .color(color);

        for (int i = 0; i < arr_pos.size(); i++)
            rectLine.add(arr_pos.get(i));

        return rectLine;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i).getNodeName().equals(nodename)) {
                return i;
            }
        }

        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {
        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        int index = 0;
        int len = encoded.length();
        int lat = 0;
        int lng = 0;

        while (index < len) {
            int b;
            int shift = 0;
            int result = 0;

            do {
                b = encoded.charAt(index++) - 63;
                result |= ((b & 0x1f) << shift);
                shift += 5;
            } while (b >= 0x20);

            int dlat = (((result & 1) != 0) ? (~(result >> 1)) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;

            do {
                b = encoded.charAt(index++) - 63;
                result |= ((b & 0x1f) << shift);
                shift += 5;
            } while (b >= 0x20);

            int dlng = (((result & 1) != 0) ? (~(result >> 1)) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(position);
        }

        return poly;
    }

    //Convert dp to pixel
    private int dpToPx(int dp) {
        DisplayMetrics displayMetrics = myContext.getResources()
                                                 .getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

        return px;
    }

    public void setOnDirectionResponseListener(
        OnDirectionResponseListener listener) {
        mDirectionListener = listener;
    }

    public interface OnDirectionResponseListener {
        public void onResponse(String status, Document doc, GoogleDirection gd);
    }

    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();
        }
    }
}

and this is my main class : import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.FragmentActivity;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.w3c.dom.Document;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private GoogleDirection gd;
    private LatLng Arret=new LatLng(30.413647, -9.555608);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        gd = new GoogleDirection(this);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            mMap.setMyLocationEnabled(true);
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {

        MyLocation loc=new MyLocation(this);
        mMap.addMarker(new MarkerOptions().position(new LatLng(loc.getLatitude(),loc.getLongitude()))
                .icon(BitmapDescriptorFactory.defaultMarker(
                        BitmapDescriptorFactory.HUE_BLUE)));
        mMap.addMarker(new MarkerOptions().position(Arret)
                .icon(BitmapDescriptorFactory.defaultMarker(
                        BitmapDescriptorFactory.HUE_BLUE)));
        gd.setOnDirectionResponseListener(new GoogleDirection.OnDirectionResponseListener() {
            @Override
            public void onResponse(String status, Document doc, GoogleDirection gd) {
                mMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
                gd.getTotalDurationValue(doc);
            }
        });
        gd.setLogging(true);
        //LatLng test=new LatLng((loc.getLatitude()+0.1f),(loc.getLongitude()+0.5f));
        gd.request(new LatLng(loc.getLatitude(),loc.getLongitude()), Arret , GoogleDirection.MODE_WALKING);

    }
}

解决方案

Use a Listener Listener for that. Example in 2 minutes.

Use an Interface like:

public interface OnTaskCompleted{
    void onTaskCompleted(Document doc);
}

Extend your Activity with this Interface:

public YourActivity implements OnTaskCompleted{
   //your Activity
}

Let the AsyncTask send an information when it's done.

public YourTask extends AsyncTask<Object,Object,Object>{ 
private OnTaskCompleted listener;

// all your stuff
public YourTask(OnTaskCompleted listener){
    this.listener=listener;
}

protected void onPostExecute(Object o){
    listener.onTaskCompleted(doc);
}
}

Now you implement the onTaskCompleted in your activity and handle the Document which has been given by the asynctask.

这篇关于如何从AsyncTask的返回一个对象主类的android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆