Search Google Places Search System.err

I am trying to find a restaurant by name using an AutoCompleteTextView that gets the seat ids successfully. I also checked the HTTP request manually in my browser which is responding with correct information. When this code is executed, system.err is displayed in the LogCat console in Eclipse. My code is below;

public class AdvancedSearch extends Activity implements OnItemClickListener {

    private static final String LOG_TAG = "com.lw276.justdine";

    private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
    private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
    private static final String OUT_JSON = "/json";

    // ------------ make your specific key ------------
    private static final String API_KEY = "MyAPIKEY";

    private Activity context = this;
    static HashMap<String, String> place;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advanced_search);
        final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
        autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this,
                R.layout.list_item));
        autoCompView.setOnItemClickListener(this);
        Button btnAdvancedSearch = (Button) findViewById(R.id.advanced_search_btn);
        btnAdvancedSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = autoCompView.getText().toString();
                if(place.containsKey(str)){
                    String placeId = place.get(str);
                    Log.d("advancedSearchBtn: placeId = ", placeId);
                    Log.i("advancedSearchBtn", "Search button has been pressed");
                    Intent i = new Intent(context, GoogleMap.class);
                    i.putExtra("advancedSearch", placeId);
                    startActivity(i);
                } else {
                    Toast.makeText(context, "Please select an item from the autocomplete list", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    public void onItemClick(AdapterView<?> adapterView, View view,
            int position, long id) {
//      String str = (String) adapterView.getItemAtPosition(position);
//      Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    public static ArrayList<String> autocomplete(String input) {
        ArrayList<String> resultList = null;

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(PLACES_API_BASE
                    + TYPE_AUTOCOMPLETE + OUT_JSON);
            sb.append("?key=" + API_KEY);
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));
            URL url = new URL(sb.toString());
            System.out.println("URL: " + url);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error processing Places API URL", e);
            return resultList;
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to Places API", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
            resultList = new ArrayList<String>(predsJsonArray.length());
            place = new HashMap<String, String>();
            for (int i = 0; i < predsJsonArray.length(); i++) {
                    System.out.println(predsJsonArray.getJSONObject(i).getString(
                            "description"));
                    System.out
                            .println("============================================================");
                    resultList.add(predsJsonArray.getJSONObject(i).getString(
                            "description"));

                 String description = predsJsonArray.getJSONObject(i).getString("description");
                 String placeId = predsJsonArray.getJSONObject(i).getString("place_id");
                 place.put( description, placeId);
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }
        return resultList;
    }

    class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String>
            implements Filterable {
        private ArrayList<String> resultList;

        public GooglePlacesAutocompleteAdapter(Context context,
                int textViewResourceId) {
            super(context, textViewResourceId);
        }

        @Override
        public int getCount() {
            return resultList.size();
        }

//      @Override
//      public HashMap<String, String> getItem(int index) {
//         return resultList.get(index);
//      }

        @Override
        public String getItem(int index){
            return resultList.get(index);
        }

        @Override
        public Filter getFilter() {
            Filter filter = new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults filterResults = new FilterResults();
                    if (constraint != null) {
                        // Retrieve the autocomplete results.
                        resultList = autocomplete(constraint.toString());

                        // Assign the data to the FilterResults
                        filterResults.values = resultList;
                        filterResults.count = resultList.size();
                    }
                    return filterResults;
                }

                @Override
                protected void publishResults(CharSequence constraint,
                        FilterResults results) {
                    if (results != null && results.count > 0) {
                        notifyDataSetChanged();
                    } else {
                        notifyDataSetInvalidated();
                    }
                }
            };
            return filter;
        }
    }

}

      

Example googlePlaces =

https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJCSWGvY-FdUgRpGdg10FTIIg&key="MY_API_KEY"

      

Is it obvious to everyone why no markers are placed on my map tile?

Errors from LogCat: http://pastebin.com/T1AFbw3s

Google Maps and Markers Class: http://pastebin.com/hT2XwuE2

+3


source to share


2 answers


It turns out that since I used the same code to add markers to the map, when the granular search was used to identify one place, the JSONArray type is incompatible with the result set ... If that makes sense. I had to separate them by checking if there was a nearby search or a search for details. Below is the code to find information:



resultObject = resultObject.getJSONObject("result"); // <---
                    places = new MarkerOptions[1];
                    LatLng placeLL = null;
                    String placeName = "";
                    String vicinity = "";
                    try {
                        JSONObject placeObject = resultObject;
                        JSONObject loc = placeObject.getJSONObject(
                                "geometry").getJSONObject("location");
                        placeLL = new LatLng(Double.valueOf(loc
                                .getString("lat")), Double.valueOf(loc
                                .getString("lng")));
                        vicinity = placeObject.getString("vicinity");
                        placeName = placeObject.getString("name");
                    } catch (JSONException jse) {
                        missingValue = true;
                        jse.printStackTrace();
                    }
                    if (missingValue){
                        result = null;
                    } else {
                        places[0] = new MarkerOptions().position(placeLL)
                                .title(placeName).snippet(vicinity);
                    }

      

0


source


  • The error thrown because of incorrect parsing of Json on line 193 of the action GoogleMap

    :

       JSONArray placesArray = resultObject.getJSONArray("results");
    
          

I believe the key is result

instead results

. I can give you a better explanation if I see the json response. In the meantime, I also suggest that you use a library Gson

to parse json responses to objects instead of manually mapping them. It would be much easier.



  1. Markers

    must be added manually:

    private void addMarker(String name, double lat, double long){
       LatLng latlong = LatLng.newInstance(lat, long);
       MarkerOptions markerOptions = MarkerOptions.newInstance();
       markerOptions.setIcon(Icon.newInstance("/img/icon.png"));
       markerOptions.setTitle(name);  
       Marker marker = new Marker(latlong, markerOptions);
       map.addOverlay(marker);
    }
    
          

+1


source







All Articles