使用GoogleMaps API计算两个位置点之间的距离时,遇到空指针异常

时间:2018-06-21 15:57:54

标签: android json google-maps google-maps-api-3

我正在尝试获取两个地方之间的距离,我的原点纬度和经度已在程序中进行了硬编码,目标纬度和经度是通过对搜索框中的用户输入进行地理编码来检索的

但是当我单击MapsActivity.java中执行onClick()方法的按钮时,会显示以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONObject.<init>(JSONObject.java:156)
    at org.json.JSONObject.<init>(JSONObject.java:173)
    at com.example.itachi.com.mmaps.DataParser.parseDirections(DataParser.java:55)
    at com.example.itachi.com.mmaps.GetDirectionsData.onPostExecute(GetDirectionsData.java:30)
    at com.example.itachi.com.mmaps.GetDirectionsData.onPostExecute(GetDirectionsData.java:9)
    at android.os.AsyncTask.finish(AsyncTask.java:651)
    at android.os.AsyncTask.-wrap1(AsyncTask.java)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5461)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

MapsActivity.java:

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleMap mMap;
    //Google Api
    private GoogleApiClient client;
    //Location Request Object
    private LocationRequest locationRequest;
    //Location
    private Location lastLocation;
    //Marker
    private Marker currentLocation;
    //Request Location Code
    public static final int REQUEST_LOCATION_CODE = 99;
    //Origin lat lang
    double latitude,longitude;
    //destination lat lang
    double end_latitude, end_longitude;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            checkLocationPermission();
        }

        // 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);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode){
            case REQUEST_LOCATION_CODE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    //WHEN PERMISSIONS ARE GRANTED
                    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                        if(client == null){
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }
                }
                else {
                    Toast.makeText(this, "Permissions Denied", Toast.LENGTH_SHORT).show();
                }
                return;
        }
    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
       if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
           buildGoogleApiClient();
           mMap.setMyLocationEnabled(true);
       }


    }

    protected synchronized void buildGoogleApiClient() {
        //Here we build out Google api and then connect

        client = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this).addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
        client.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        //Here we request the location regularly and update the location for a specific interval

        locationRequest = new LocationRequest();
        locationRequest.setInterval(1000);
        locationRequest.setFastestInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //noinspection deprecation
            LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
        }


    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {
        lastLocation = location;
        //Checking if there is any previous location shared
        if(currentLocation != null){
            //if there is any other location shared remove it
            currentLocation.remove();
        }
        //getting the lat and lang of the location and saving them to LatLang
        LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());

        //Setting the marker like its properties , position and etc,.,.
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latlng);
        markerOptions.title("Current Location");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        //Appending these properties to the marker
        currentLocation = mMap.addMarker(markerOptions);
        //Move the screen as per the locations saved
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
        mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
        //After getting the location and updating the marker we have to stop requesting
        if(client != null){
            //removing the location updating api
            //noinspection deprecation
            LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
        }

    }

    //Create a method to check the permissions
    public boolean checkLocationPermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)){
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);
            }
            else{
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_LOCATION_CODE);

            }
            return false;
        }
        return true;
    }


    public void onClick(View view){
        if(view.getId() == R.id.B_search){
            mMap.clear();
            //Collecting the distance using api
            Object dataTransfer[] = new Object[2];
            String url = getDirectionUrl();
            GetDirectionsData getDirectionsData = new GetDirectionsData();
            dataTransfer[0] = mMap;
            dataTransfer[1] = url;

            getDirectionsData.execute(dataTransfer);


            // collecting the text entered by the person
            EditText tf_location = findViewById(R.id.TF_Location);
            String location = tf_location.getText().toString();
            List<Address> addressList = null;
            MarkerOptions mo = new MarkerOptions();

            if(location != ""){
                //create an object for geocoding the location
                Geocoder geoCoder = new Geocoder(this);

                try {
                    addressList = geoCoder.getFromLocationName(location, 5);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                for (int i=0; i<addressList.size();i++){
                    Address myAddress = addressList.get(i);
                    LatLng latLng = new LatLng(myAddress.getLatitude(),myAddress.getLongitude());
                    end_latitude = myAddress.getLatitude();
                    end_longitude = myAddress.getLongitude();
                    Log.d("lat by pavan gadu",String.valueOf(end_latitude));
                    Log.d("lon",String.valueOf(end_longitude));
                    mo.position(latLng);
                    mo.title("search results");
                    mMap.addMarker(mo);
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                }
            }
        }
    }
    private String getDirectionUrl(){
        latitude = 15.5997300;
        longitude = 79.6064320;
        StringBuilder googleDorectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
        //append the origin(tghis is of three ways -1.)send the place name , 2.)send the place lat lang 3.)send the place id
        googleDorectionsUrl.append("origin"+latitude+","+longitude);
        //append the destination
        googleDorectionsUrl.append("&destination"+end_latitude+","+end_longitude);
        //append the key
        googleDorectionsUrl.append("&key="+"AIzaSyCAcfy-02UHSu2F6WeQ1rhQhkCr51eBL9g");
        //return the url
        Log.d("Url sending pan gadu:",googleDorectionsUrl.toString());
        return  googleDorectionsUrl.toString();

    }
}

GetDirectionsData.java类:

public class GetDirectionsData extends AsyncTask<Object, String, String> {
String url;
GoogleMap mMap;
String googleDirectionsData;
@Override
protected String doInBackground(Object... objects) {
    mMap = (GoogleMap) objects[0];
    url = (String)objects[1];
    DownloadUrl downloadUrl = new DownloadUrl();
    try {
        googleDirectionsData = downloadUrl.readUrl(url);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return googleDirectionsData;
}
@Override
protected void onPostExecute(String s) {
    HashMap<String, String> directionsList = null;
    DataParser parser = new DataParser();
    directionsList = parser.parseDirections(s);
}

}

DataParser.java类:

public class DataParser {
private HashMap<String, String> getPlace(JSONObject googlePlaceJson){
    //Detailos about the place are being stored in the hashmap
    HashMap<String, String> googlePlacesMap = new HashMap<>();
    //Declaring all the primary data of the place to strings
    String placeName = "-NA-";
    String vicinity = "-NA-";
    String latitude = "";
    String longitude = "";
    String reference = "";
    //fetching dta from the given JSON object and parsing to string
    try{
        if(!googlePlaceJson.isNull("name")){

            placeName = googlePlaceJson.getString("name");

        }
        if(!googlePlaceJson.isNull("vicinity")){

            vicinity = googlePlaceJson.getString("vicinity");
        }
        latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
        longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");

        reference =  googlePlaceJson.getString("reference");

        googlePlacesMap.put("place_name", placeName);
        googlePlacesMap.put("vicinity", vicinity);
        googlePlacesMap.put("lat", latitude);
        googlePlacesMap.put("lng", longitude);
        googlePlacesMap.put("reference", reference);


    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    //finally return the data
    return  googlePlacesMap;
}
public HashMap<String, String> parseDirections (String jsonData){
    JSONArray jsonArray = null;
    JSONObject jsonObject;
    try {
        jsonObject = new JSONObject(jsonData);
        jsonArray = jsonObject.getJSONArray("routs");


    } catch (JSONException e) {
        e.printStackTrace();
    }
    return  getDuration(jsonArray);
}

private HashMap<String, String> getDuration(JSONArray googleDirectionsJson){
    HashMap<String, String> googleDirectionsMap = new HashMap<>();
    String duration = "";
    String distance = "";
    Log.d("Json response",googleDirectionsJson.toString());

    return googleDirectionsMap;
}

}

DownloadUrl.java是:

    public String readUrl(String myUrl){

    String data ="";
    InputStream inputStream = null;
    HttpURLConnection urlConnection = null;
    try {
        //getting the url
        URL url = new URL(myUrl);
        //open connection
        urlConnection = (HttpURLConnection) url.openConnection();
        //connect the url
        urlConnection.connect();
        Log.d("message",":in urldownload");

        //Read the data
        inputStream = urlConnection.getInputStream();
        //feed it to BufferReader
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        //open a string buffer
        StringBuffer sb = new StringBuffer();


        String line = "";
        while((line = br.readLine()) != null){
            //append all the data present in the string buffer in line(which is the string object)
            sb.append(line);
        }
        //parse the string buffer to actual string and save in data variabke
        data = sb.toString();
        //close the buffer
        br.close();


    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            //close the streem buffer and url connection
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        urlConnection.disconnect();
    }

    return data;

}

}

0 个答案:

没有答案