当我标记第二个指针时,我收到此错误。错误行我将其称为//错误

时间:2018-04-19 07:28:24

标签: android google-maps google-directory-api

 package com.example.ronaldbenjamin.mapdirection;
    import android.Manifest; import android.annotation.SuppressLint;
    import android.content.pm.PackageManager; import
    android.graphics.Color; import android.os.AsyncTask; import
    android.support.annotation.NonNull; import
    android.support.v4.app.ActivityCompat; import
    android.support.v4.app.FragmentActivity; import android.os.Bundle;
    import android.widget.Toast;

    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.BitmapDescriptor; 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
    com.google.android.gms.maps.model.PolylineOptions;

    import org.json.JSONException; import org.json.JSONObject;

    import java.io.BufferedReader; import java.io.IOException; import
    java.io.InputStream; import java.io.InputStreamReader; import
    java.net.HttpRetryException; import java.net.HttpURLConnection;
    import java.net.MalformedURLException; import java.net.URL; import
    java.util.ArrayList; import java.util.HashMap; import
    java.util.List;

    public class MapsActivity extends FragmentActivity implements
    OnMapReadyCallback {

        private GoogleMap mMap;
        private static final int LOCATION_REQUEST=500;
        ArrayList<LatLng>  listPoints;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
            listPoints=new ArrayList<>();


        }


        /**
         * Manipulates the map once available.
         * This callback is triggered when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera. In this case,
         * we just add a marker near Sydney, Australia.
         * If Google Play services is not installed on the device, the user will be prompted to install
         * it inside the SupportMapFragment. This method will only be triggered once the user has
         * installed Google Play services and returned to the app.
         */
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.getUiSettings().setZoomControlsEnabled(true);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
    PackageManager.PERMISSION_GRANTED &&
    ActivityCompat.checkSelfPermission(this,
    Manifest.permission.ACCESS_COARSE_LOCATION) !=
    PackageManager.PERMISSION_GRANTED) {
              ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST);
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
                @Override
                public void onMapLongClick(LatLng latLng) {

                    //reset marker when 2
                    if(listPoints.size()== 2){
                        listPoints.clear();
                        mMap.clear();
                    }
                    //save first point select
                    listPoints.add(latLng);
                    //create marker
                    MarkerOptions markerOptions=new MarkerOptions();
                    markerOptions.position(latLng);
                    if (listPoints.size()== 1){
                        //Add first marker to the map
                        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                    }else{
                        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

                    }
                    mMap.addMarker(markerOptions);

                    //TODO: reqest direction
                    if (listPoints.size()==2){

                        String url=getRequestUrl(listPoints.get(0),listPoints.get(1));
                        TaskRequestDirections taskRequestDirections=new TaskRequestDirections();
                        taskRequestDirections.execute(url);


                    }



                }
            });

        }

        private String getRequestUrl(LatLng origin, LatLng dest) {
         //values of origin
            String str_org="origin=" +origin.latitude+","+origin.longitude;

            String str_dest="destination" + dest.latitude+","+dest.longitude;

            String sensor="sensor-false";

            String mode="mode-driving";

            String param= str_org+"&"+str_dest+"&" +sensor+"&" +mode;

            String output="json";
            String url="https://maps.googleapis.com/maps/api/directions/" + output +
    "?" +param;
             return url;

        }

        private  String requestDirection(String reqUrl) throws IOException {
            String responseString=" ";
            InputStream inputStream=null;
            HttpURLConnection httpURLConnection=null;

            try{
                URL url=new URL(reqUrl);
                httpURLConnection= (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();

                inputStream=httpURLConnection.getInputStream();
                InputStreamReader inputStreamReader= new InputStreamReader(inputStream);
                BufferedReader bufferedReader= new BufferedReader(inputStreamReader);

                StringBuffer stringBuffer= new StringBuffer();
                String line="";
                while ((line =bufferedReader.readLine())!=null){
                    stringBuffer.append(line);

                }
                responseString=stringBuffer.toString();
                bufferedReader.close();
                inputStreamReader.close();



            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if (inputStream != null){
                    inputStream.close();
                }
                httpURLConnection.disconnect();
            }
            return responseString;

        }


        @SuppressLint("MissingPermission")
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

            switch (requestCode){
                case LOCATION_REQUEST:
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                        mMap.setMyLocationEnabled(true);



                    }
                    break;

            }

        }

        public class TaskRequestDirections extends AsyncTask<String,Void,String>{

            @Override
            protected String doInBackground(String... strings) {
                String responseString=" ";
                try {
                    responseString=requestDirection(strings[0]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return responseString;

            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                //Parse jason

                TaskParser taskParser=new TaskParser();
                taskParser.execute(s);

            }
        }
        public class TaskParser extends AsyncTask<String,Void, List<List<HashMap<String, String>>>> //errror
        {

            @Override
            protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
                JSONObject jsonObject=null;
                List<List<HashMap<String, String>>> routes=null;
                try {
                    jsonObject=new JSONObject(strings[0]);
                    DirectionParser directionParser=new DirectionParser();
                    routes=directionParser.parse(jsonObject);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return routes;

            }

            @Override
            protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
                ArrayList points=null;
                PolylineOptions polylineOptions=null;
                for(List<HashMap<String, String>>  path:lists)/// error {
                    points=new ArrayList();
                    polylineOptions=new PolylineOptions();
                    for (HashMap<String, String> point:path){
                        double lat=Double.parseDouble(point.get("lat"));
                        double lon=Double.parseDouble(point.get("lon"));

                        points.add(new LatLng(lat,lon));


                    }
                    polylineOptions.addAll(points);
                    polylineOptions.width(15);
                    polylineOptions.color(Color.BLUE);
                    polylineOptions.geodesic(true);

                }
                if (polylineOptions!=null){
                   mMap.addPolyline(polylineOptions);

                }
                else
                {
                    Toast.makeText(getApplicationContext(),"direction not found",Toast.LENGTH_SHORT).show();
                }
            }
        } }
  

:致命的例外:主要                         处理:com.example.ronaldbenjamin.mapdirection,PID:23351                         java.lang.NullPointerException:尝试调用接口方法&#39; java.util.Iterator java.util.List.iterator()&#39;   在...上       null对象引用                             在输入代码herecom.example.ronaldbenjamin.mapdirection.MapsActivity $ TaskParser.onPostExecute(MapsActivity.java:239) strong       文本                             at com.example.ronaldbenjamin.mapdirection.MapsActivity $ TaskParser.onPostExecute(MapsActivity.java:216)

0 个答案:

没有答案