有什么方法可以等待任务完成,然后恢复执行我的代码? Android Studio Java

发布于 2025-01-30 06:55:03 字数 5859 浏览 2 评论 0原文

我正在做一个拼车Android应用程序,用户可以在其中请求和提供游乐设施。 我的问题是搜索乘客的乘客结果。我的目标是考虑到所有游乐设施:日期,时间,来源和目的地。 我正在测试以检查乘客的源和目标坐标是否在驾驶员路径上/附近,但我发现在回收卡视图中显示卡之前,我发现困难等待响应。

#searchResults.java#

FirestoreRecyclerAdapter<Ride, MyViewHolder> adapter = new FirestoreRecyclerAdapter<Ride, SearchResults.MyViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull MyViewHolder holder, int position, @NonNull Ride model) {
            driverOriginCoordinates = geoLocate(model.getSource());
            Log.d(TAG, "driverOrigin: "+driverOriginCoordinates);
            Log.d(TAG, "passengerOrigin: "+passengerOriginCoordinates);
            driverDestinationCoordinates = geoLocate(model.getDestination());
            Log.d(TAG, "driverDest: "+driverDestinationCoordinates);
            Log.d(TAG, "passengerDest: "+passengerDestinationCoordinates);

            String url = getDirectionsUrl(driverOriginCoordinates,driverDestinationCoordinates);
            DownloadTask downloadTask = new DownloadTask();
            try {
                downloadTask.execute(url).get();
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }

            if (isSourceValid && isDestinationValid){
                Toast.makeText(SearchResults.this, "Hello", Toast.LENGTH_SHORT).show();
                holder.setSource(model.getSource());
                holder.setDestination(model.getDestination());
                holder.setSeats(Integer.parseInt(model.getNbFreeSeats()));
                holder.setPrice(Double.parseDouble(model.getCost()));
                firebaseFirestore.collection("user").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {

                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();

                        for (DocumentSnapshot d : list) {
                            if (d.get("uid").toString().equals(model.getIdOwner())){
                                holder.setDriverName(d.get("First Name").toString()+" "+d.get("Last Name").toString());

                            }
                        }
                    }
                });
                firebaseFirestore.collection("car").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {

                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();

                        for (DocumentSnapshot d : list) {
                            if (d.get("licencePlate").toString().equals(model.getIdCar())){
                                holder.setCarBrandModelYear(d.get("brand").toString()+" | "+d.get("model").toString()+" ("+d.get("year").toString()+")");

                            }
                        }
                    }
                });
            }
        }

我想等待下载task.execute(url).get()完成,因为Issourcevalid和isDestinationValid取决于它。

#downloadtask##

public class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String data = "";
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        SearchResults.ParserTask parserTask = new SearchResults.ParserTask();
        try {
            parserTask.execute(result).get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

parsertask#

public class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList points = new ArrayList();
        PolylineOptions lineOptions = new PolylineOptions();
        for (int i = 0; i < result.size(); i++) {
            List<HashMap<String, String>> path = result.get(i);
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);
                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                points.add(position);
            }
            lineOptions.addAll(points);
            lineOptions.geodesic(true);
        }
        Log.d(TAG, "PolyLine: "+lineOptions.getPoints());

        isSourceValid = PolyUtil.containsLocation(passengerOriginCoordinates, lineOptions.getPoints(),true);
        isDestinationValid = PolyUtil.containsLocation(passengerDestinationCoordinates,lineOptions.getPoints(),true);

        Log.d(TAG, "boolSource: "+isSourceValid);
        Log.d(TAG, "boolDest: "+isDestinationValid);
    }
}

I'm doing a carpooling android app in which users can request and offer rides.
My problem is in searching the results for the rides as a passenger. My goal is to display all rides taking into consideration: date, time, source and destination.
I'm testing to check if the source and destination coordinates of the passenger are on/near the path of the driver but i am finding difficulties waiting for the response before displaying the cards in the recycler view.

#SearchResults.java#

FirestoreRecyclerAdapter<Ride, MyViewHolder> adapter = new FirestoreRecyclerAdapter<Ride, SearchResults.MyViewHolder>(options) {
        @Override
        protected void onBindViewHolder(@NonNull MyViewHolder holder, int position, @NonNull Ride model) {
            driverOriginCoordinates = geoLocate(model.getSource());
            Log.d(TAG, "driverOrigin: "+driverOriginCoordinates);
            Log.d(TAG, "passengerOrigin: "+passengerOriginCoordinates);
            driverDestinationCoordinates = geoLocate(model.getDestination());
            Log.d(TAG, "driverDest: "+driverDestinationCoordinates);
            Log.d(TAG, "passengerDest: "+passengerDestinationCoordinates);

            String url = getDirectionsUrl(driverOriginCoordinates,driverDestinationCoordinates);
            DownloadTask downloadTask = new DownloadTask();
            try {
                downloadTask.execute(url).get();
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }

            if (isSourceValid && isDestinationValid){
                Toast.makeText(SearchResults.this, "Hello", Toast.LENGTH_SHORT).show();
                holder.setSource(model.getSource());
                holder.setDestination(model.getDestination());
                holder.setSeats(Integer.parseInt(model.getNbFreeSeats()));
                holder.setPrice(Double.parseDouble(model.getCost()));
                firebaseFirestore.collection("user").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {

                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();

                        for (DocumentSnapshot d : list) {
                            if (d.get("uid").toString().equals(model.getIdOwner())){
                                holder.setDriverName(d.get("First Name").toString()+" "+d.get("Last Name").toString());

                            }
                        }
                    }
                });
                firebaseFirestore.collection("car").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {

                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();

                        for (DocumentSnapshot d : list) {
                            if (d.get("licencePlate").toString().equals(model.getIdCar())){
                                holder.setCarBrandModelYear(d.get("brand").toString()+" | "+d.get("model").toString()+" ("+d.get("year").toString()+")");

                            }
                        }
                    }
                });
            }
        }

I want to wait for downloadTask.execute(url).get() to finish because isSourceValid and isDestinationValid depends on it.

#DownloadTask#

public class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String data = "";
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        SearchResults.ParserTask parserTask = new SearchResults.ParserTask();
        try {
            parserTask.execute(result).get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

#ParserTask#

public class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {

    // Parsing the data in non-ui thread
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;

        try {
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();
            routes = parser.parse(jObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return routes;
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList points = new ArrayList();
        PolylineOptions lineOptions = new PolylineOptions();
        for (int i = 0; i < result.size(); i++) {
            List<HashMap<String, String>> path = result.get(i);
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);
                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                points.add(position);
            }
            lineOptions.addAll(points);
            lineOptions.geodesic(true);
        }
        Log.d(TAG, "PolyLine: "+lineOptions.getPoints());

        isSourceValid = PolyUtil.containsLocation(passengerOriginCoordinates, lineOptions.getPoints(),true);
        isDestinationValid = PolyUtil.containsLocation(passengerDestinationCoordinates,lineOptions.getPoints(),true);

        Log.d(TAG, "boolSource: "+isSourceValid);
        Log.d(TAG, "boolDest: "+isDestinationValid);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文