有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

另一个AsyncTask的onPostExecute中的java AsyncTask并返回结果

在我的第一个AsyncTask doInBackground方法中,我运行了一个从Google Place Api获取位置列表的方法。在第一个异步任务的postExecute中,我获得了这些地方的所有名称,并在列表视图中显示它们

现在我想展示一个地方距离我当前位置的行驶距离(我已经可以得到了)。为此,我在另一个类中创建了另一个AsyncTask来获得这个距离。以下是代码:

public class Distance extends AsyncTask<Double, Double, String> {
    GooglePlaces googlePlaces;
    String distancePlace = null;
    @Override
    final protected String doInBackground(Double... params) {
        double lat1,lat2,lon1,lon2;
        lat1=params[0];
        lon1=params[1];
        lat2=params[2];
        lon2=params[3];
        googlePlaces = new GooglePlaces();
        distancePlace= googlePlaces.getDistance(lat1,lon1,lat2,lon2);
        return distancePlace;
    }
}

这是我的第一个AsyncTask postExecute的代码:

    protected void onPostExecute(String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //get json status
                String status = nearPlaces.status;
                if (status.equals("OK")){
                    if (nearPlaces.results != null){
                        //every single place
                        for (Place p : nearPlaces.results){
                        //just a try, here I would like to get the distance
                         /*
                            Double[] myparams = {gps.getLatitude(),gps.getLongitude(),
                                    p.geometry.location.lat,p.geometry.location.lng};
                            new Distance().execute(myparams);*/

                            HashMap<String,String> map = new HashMap<String, String>();
                                map.put(KEY_NAME,p.name);
                                //add hashmap
                                placesListItems.add(map);
                          }
                        ListAdapter adapter = new SimpleAdapter(GpsActivity.this, placesListItems, R.layout.list_item, new String[] {KEY_REFERENCE,KEY_NAME},
                                new int[] {R.id.reference, R.id.name});
                        //add into listview
                        lv.setAdapter(adapter);
                    }

我的问题是如何在postExecute中执行“distance AsyncTask”,并将其结果返回到我的第一个AsyncTask中,以在我的ListView中显示它


共 (1) 个答案

  1. # 1 楼答案

    你可以这样做:

    Distance distance = new Distance(){
        protected void onPostExecute(final String result1) {
            // First AsyncTask result.
            Distance distance2 = new Distance(){
                protected void onPostExecute(String result2) {
                    // process the second result. 
                    // Because the first result "result1" is "final", 
                    // it can be accessed inside this method.
                }
            };
            distance2.execute(...);
        }
    };
    distance.execute(...);
    

    此外,您不需要使用runOnUiThread(...),因为onPostExecute(...)方法是在UI线程上执行的