我需要在地图上显示巴士位置,我的数据库中保存了纬度和经度。要检索纬度和经度,我正在使用 AsynTask。但我认为我的代码存在一些问题,如果在 onMapReady 中调用 AsyncTask,应用程序会崩溃。我检查了没有调用 AsyncTask 提供手动纬度和经度,它工作正常。请帮我解决问题。
这是我的代码:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
GetLocation getLocation = new GetLocation(getApplicationContext());
getLocation.execute();
}
public class GetLocation extends AsyncTask<String,Void,String> {
Context context;
GetLocation(Context ctx){
context = ctx;
}
@Override
protected String doInBackground(String... params) {
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
String login_url = "https://www.mywebsite.com/android/getlonglatt.php";
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result="";
while ((line = bufferedReader.readLine())!=null){
result += line;
}
JSONObject jsonObject = new JSONObject(result);
String latitudedb = (String) jsonObject.get("latitude");
String longitudedb = (String) jsonObject.get("longitude");
String busnum = (String) jsonObject.get("busnum");
Double newlatt = Double.valueOf(latitudedb);
Double newlong = Double.valueOf(longitudedb);
LatLng location = new LatLng(newlatt, newlong);
MarkerOptions options = new MarkerOptions().position(location).title(busnum);
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,19.2f));
bufferedReader.close();
httpURLConnection.disconnect();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onProgressUpdate(Void... values) {
}
}