Question

i was developing app in android to get my nearby places and when i tried to run i made everything but got this exception and i do not know what is the reason to cause this exception. Please Helppp

LogCat

02-24 02:26:03.366: E/Trace(21173): error opening trace file: No such file or directory     (2)

02-24 02:26:04.562: E/GooglePlayServicesUtil(21173): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

02-24 02:26:11.773: E/AndroidRuntime(21173): FATAL EXCEPTION: main

02-24 02:26:11.773: E/AndroidRuntime(21173): java.lang.NullPointerException

02-24 02:26:11.773: E/AndroidRuntime(21173):    at com.appscourt.maps.places.near.me.MainActivity$ParserTask.onPostExecute(MainActivity.java:270)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at com.appscourt.maps.places.near.me.MainActivity$ParserTask.onPostExecute(MainActivity.java:1)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at android.os.AsyncTask.finish(AsyncTask.java:631)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at android.os.AsyncTask.access$600(AsyncTask.java:177)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at android.os.Handler.dispatchMessage(Handler.java:99)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at android.os.Looper.loop(Looper.java:137)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at android.app.ActivityThread.main(ActivityThread.java:5059)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at java.lang.reflect.Method.invokeNative(Native Method)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at java.lang.reflect.Method.invoke(Method.java:511)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)

02-24 02:26:11.773: E/AndroidRuntime(21173):    at dalvik.system.NativeStart.main(Native Method)

MainActivity

public class MainActivity extends FragmentActivity implements LocationListener {

GoogleMap googleMap;
Spinner placeTypeSpinner;

String[] placeType = null;
String[] placeTypeName = null;

double latitude = 0;
double longitude = 0;

Button btnFind;

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

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

    //Array of places type
    placeType = getResources().getStringArray(R.array.place_type);

    //Array of places type name
    placeTypeName = 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, placeTypeName);

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

    //Setting adapter on spinner to set place types
    placeTypeSpinner.setAdapter(adapter);

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

    //Getting google play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
    if(status != ConnectionResult.SUCCESS) {
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();
    } else { //Google Play Services are available

        //Getting reference to the SupportMapFragment
        googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
        googleMap.setMyLocationEnabled(true);

        LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);

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

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

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

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

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

        googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

                @Override
                public void onInfoWindowClick(Marker marker) {

                     Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
                     String reference = mMarkerPlaceLink.get(marker.getId());
                        intent.putExtra("reference", reference);

                        // Starting the Place Details Activity
                        startActivity(intent);
                }
            });
        btnFind.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int selectedPos = placeTypeSpinner.getSelectedItemPosition();
                String type = placeType[selectedPos];

                StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
                sb.append("location=" + latitude + "," + longitude);
                sb.append("&radius = 5000");
                sb.append("&types = "+type);
                sb.append("&sensor = true");
                sb.append("&key = AIzaSyAbz9kNQKmgGRZJJj5fGcrp4DyfyvbxHm8");
                // Creating a new non-ui thread task to download json data
                PlacesTask placesTask = new PlacesTask();
                // Invokes the "doInBackground()" method of the class PlaceTask
                placesTask.execute(sb.toString());
            }
        });
    }
    //initializeMap();
}

/** A method to download json data from url */
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;
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

public class PlacesTask extends AsyncTask<String, Integer, String>{

    String data = null;
    //MainActivity mainActivity = new MainActivity();
    // 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;
    }

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

public class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;
    //MainActivity mainActivity = new MainActivity();
    //GoogleMap gMap;
    //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;
    }

    @Override
    protected void onPostExecute(List<HashMap<String, String>> list) {
        //Clear all existing markers
        //gMap = mainActivity.googleMap;
        googleMap.clear();

        super.onPostExecute(list);

        for(int i = 0 ;  i < list.size() ; i++) {
            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
            googleMap.addMarker(markerOptions);
        }
    }

}

}

Was it helpful?

Solution

I think you are using Google's places api using HTTP GET. Like https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=Your_key.
While using GET method, be careful about the white spaces.
Inside your code, there are spaces on both sides of " = ". So format your StringBuilder without spaces and try again.

 StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
            sb.append("location=" + latitude + "," + longitude);
            sb.append("&radius=5000"); // take care of spaces here 
            sb.append("&types="+type); //
            sb.append("&sensor=true"); //
            sb.append("&key=Your_KEY"); //

After building your url, Log it and copy-paste it inside a web browser to check it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top