当前位置: 首页 > 知识库问答 >
问题:

NullPointer Exception for googleplacesapi

满和安
2023-03-14

我正在为谷歌地图创建一个应用程序。我正在显示地图和我的当前位置,但当我按下查找按钮时,下面的应用程序崩溃了

日志目录:-

java.lang.reflect.Method.invokejava.lang.reflect.Method.invoke的NullPointerExcix$Method.java:525PostExec桌上(com.android.internal.os.)在MethodAndArgsCaller.run主要活动$ZygoteInit.java:739PostExecte(com.android.internal.os.ZygoteInit.main)在ZygoteInit.java:555(dalvik.system.NativeStart.main)android.os.AsyncTask.access600美元(AsyncTask.java:177)在android.os.Async任务$InternalHandler.handle消息(AsyncTask.java:644)在android.os.Handler.dispatch消息(Handler.java:99)在android.os.Looper.loop(Looper.java:137)在android.app.ActivityThread.main(ActivityThread.java:5214)在java.lang.本机(本机方法)在com.example.anand.locationplacedetailstest.(ParserTask.on)在MainActivity.java:277ZygoteInit$com.example.anand.locationplacedetailstest.(ParserTask.on)在MainActivity.java:247(android.os.AsyncTask.finish)在AsyncTask.java:631(本机方法)

public class MainActivity extends FragmentActivity implements LocationListener {

GoogleMap mGoogleMap;
Spinner mSprPlaceType;

String[] mPlaceType=null;
String[] mPlaceTypeName=null;

double mLatitude=0;
double mLongitude=0;

HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Array of place types
    mPlaceType = getResources().getStringArray(R.array.place_type);

    // Array of place type names
    mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

    // Creating an array adapter with an array of Place types
    // to populate the spinner
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

    // Getting reference to the Spinner
    mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

    // Setting adapter on Spinner to set place types
    mSprPlaceType.setAdapter(adapter);

    Button btnFind;

    // Getting reference to Find Button
    btnFind = ( Button ) findViewById(R.id.btn_find);


    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());


    if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    }else { // Google Play Services are available

        // Getting reference to the SupportMapFragment
        SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting Google Map
        mGoogleMap = fragment.getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);



        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);

        mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                String reference = mMarkerPlaceLink.get(arg0.getId());
                intent.putExtra("reference", reference);

                // Starting the Place Details Activity
                startActivity(intent);
            }
        });



        // Setting click event lister for the find button
        btnFind.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                String type = mPlaceType[selectedPosition];


                StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location="+mLatitude+","+mLongitude);
                sb.append("&radius=5000");
                sb.append("&types="+type);
                sb.append("&sensor=true");
                sb.append("AIzaSyCIyZJUKAQZY6BU6V0PSCbhEILfYr8kvQI");


                // Creating a new non-ui thread task to download Google place json data
                PlacesTask placesTask = new PlacesTask();

                // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());


            }
        });

    }
}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);


        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }

    return data;
}


/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result){
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParseTask
        parserTask.execute(result);
    }

}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String,String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;
        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

        try{
            jObject = new JSONObject(jsonData[0]);

            /** Getting the parsed data as a List construct */
            places = placeJsonParser.parse(jObject);

        }catch(Exception e){
            Log.d("Exception",e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String,String>> list){

        // Clears all the existing markers
        mGoogleMap.clear();

        // this is line 277
        for(int i=0;i<list.size();i++){

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            HashMap<String, String> hmPlace = list.get(i);

            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);

            // Setting the title for the marker.
            //This will be displayed on taping the marker
            markerOptions.title(name + " : " + vicinity);

            // Placing a marker on the touched position
            Marker m = mGoogleMap.addMarker(markerOptions);

            // Linking Marker id and place reference
            mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));


        }

    }

}

共有1个答案

谭京
2023-03-14

看起来你点击谷歌地图API的网址不太正确。我认为您遗漏了“key”查询参数。

尝试更改:

sb.append("AIzaSyCIyZJUKAQZY6BU6V0PSCbhEILfYr8kvQI");

自:

sb.append("&key=AIzaSyCIyZJUKAQZY6BU6V0PSCbhEILfYr8kvQI");

仅供参考:您可以在浏览器中点击URL来查看JSON对象的结构(因为看起来您试图检索的键可能不存在)。

例如https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=32.7478,97.0928

 类似资料:

相关问答

相关文章

相关阅读