如何等待异步任务完成从数据库获取数据后再加载地图而不睡眠?

问题描述 投票:0回答:1

所以我的对象很简单,需要知道我是否可以使我的代码一直更好,或者从我的代码中删除睡眠,并以某种方式等待异步任务完成,然后在加载地图之前从数据库获取数据。

在努力弄清楚为什么我的代码无法工作之后,我应该将 5 个不同的 LOG.i 放入标记为步骤 1 到步骤 5 中,并按照我期望的运行顺序。

在我执行此操作时查看日志后,它按以下顺序运行:第 4 步,然后是 1、5、2,然后是 3。所以我添加了一个临时睡眠计时器,现在它在 logcat 中显示了以下步骤顺序 1 到 5。

我知道 10 秒的睡眠时间太长了。有没有办法在标志上进行睡眠而不是预定的时间,例如在 while 循环中。像 while vara = 0 和 varb = 0 休眠一毫秒之类的东西?

或者是否有更好的方法来编写我的代码,这样它会更高效并且根本不必使用睡眠?

下面是我当前的代码:

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.app.restaurant.bowzers.R;

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

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import java.util.concurrent.TimeUnit;

public class TruckFragment2 extends Fragment{
    double mylocationLong, mylocationLat;
    String mySB;
    GoogleMap googleMap;
    GoogleMap gMap;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Initialize view
        View view=inflater.inflate(R.layout.fragment_truck, container, false);

        mylocationLat = 39.9;
        mylocationLong = -82.83;



        getJSON("https://bowzershotdogstand.com/app/get_location.php");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Log.i("STEP 4",mylocationLong + "," + mylocationLat);
        LatLng latLng = new LatLng(mylocationLat,mylocationLong);
        // Initialize map fragment
        SupportMapFragment supportMapFragment=(SupportMapFragment)
                getChildFragmentManager().findFragmentById(R.id.truck_map);


        // Async map
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull GoogleMap googleMap) {
gMap=googleMap;
                Log.i("STEP 5", mylocationLong + "," + mylocationLat);






                     MarkerOptions markerOptions=new MarkerOptions();
                        // Set position of marker
                        markerOptions.position(latLng);
                        // Set title of marker
                        markerOptions.title(latLng.latitude+" : "+latLng.longitude);
                        // Remove all marker
//                        gMap.clear();
                        // Animating to zoom the marker
                        gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
                        // Add marker on map
                        gMap.addMarker(markerOptions);
//                    }
//                });
            }
        });

        // Return view
        return view;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void getJSON(final String urlWebService) {
        class GetJSON extends AsyncTask<Void, Void, String> {



            protected void onPreExecute() {
                super.onPreExecute();

            }

            protected void onPostExecute(String s) {
                super.onPostExecute(s);


            }

            protected String doInBackground(Void... Voids) {
                Log.i("STEP 1", urlWebService);
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append((json + "\n"));

                    }
                    Log.i("STEP 2", String.valueOf(sb));
                    mySB = String.valueOf(sb);

//                    JSONArray JA = new JSONArray(mySB);
                    JSONArray JA = new JSONArray(mySB);
                    for(int i =0 ;i <JA.length(); i++){
                        JSONObject JO = (JSONObject) JA.get(i);
                                mylocationLong = Double.parseDouble(JO.getString("longitude"));
                                mylocationLat = Double.parseDouble(JO.getString("lattitude"));
                                Log.i("STEP 3", mylocationLat + "," + mylocationLong);

                        LatLng marker = new LatLng(mylocationLong,mylocationLat);


                        gMap.clear();
                        gMap.addMarker(new MarkerOptions().position(marker).title("Marker Somewhere"));
                        gMap.moveCamera(CameraUpdateFactory.newLatLng(marker));
                                break;
                        }

                    return sb.toString().trim();

                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

}
java android android-asynctask sleep
1个回答
0
投票

我不熟悉android开发,但是在普通的java中我会考虑这段代码

CompletableFuture.supplyAsync(() -> "Your code here").get()

方法

supplyAsync(Function fn)
使您的代码在ForkJoinPool中异步执行

方法

get()
等待响应

方法

thenApply(Function fn)
thenRun(Function fn)
将您的函数应用于计算结果

© www.soinside.com 2019 - 2024. All rights reserved.