Home » Android » android – Spaces Not Working While Using Google Places Autocomplete API

android – Spaces Not Working While Using Google Places Autocomplete API

Posted by: admin June 15, 2020 Leave a comment


When I type a space into my Android app I am no longer getting any results in my drop down. How can I fix this? I am encoding the input so I am not sure why it is not working…

Before Space:
enter image description here

After Space:
enter image description here

I have looked on https://developers.google.com/places/documentation/autocomplete but I haven’t found anything to help me.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.AutoCompleteTextView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

    AutoCompleteTextView atvPlaces;
    PlacesTask placesTask;
    ParserTask parserTask;

protected void onCreate(Bundle savedInstanceState) {

    atvPlaces = (AutoCompleteTextView) findViewById(R.id.atv_places);

    atvPlaces.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            placesTask = new PlacesTask();

        public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
            // TODO Auto-generated method stub

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

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

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

        // Connecting to url

        // 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){

        data = sb.toString();


    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    return data;

// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String>{

    protected String doInBackground(String... place) {
        // For storing data from web service 
        String data = "";

        // Obtain browser key from https://code.google.com/apis/console
        String key = "key=AIzaSyDcXFSC2I6ZqxQeAbUMFvJKMrA98217H9U";

        String input="";

        try {
            input = "input=" + URLEncoder.encode(place[0], "utf-8");
        } catch (UnsupportedEncodingException e1) {

        // place type to be searched
        String types = "types=(regions)";

        // Sensor enabled
        String sensor = "sensor=false";

        // Building the parameters to the web service
        String parameters = input+"&"+types+"&"+sensor+"&"+key;

        // Output format
        String output = "json";

        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;

            // Fetching the data from we service
            data = downloadUrl(url);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        return data;

    protected void onPostExecute(String result) {

        // Creating ParserTask
        parserTask = new ParserTask();

        // Starting Parsing the JSON string returned by Web Service
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

    JSONObject jObject;

    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;

        PlaceJSONParser placeJsonParser = new PlaceJSONParser();

            jObject = new JSONObject(jsonData[0]);

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

        }catch(Exception e){
        return places;

    protected void onPostExecute(List<HashMap<String, String>> result) {

        String[] from = new String[] { "description"};
        int[] to = new int[] { android.R.id.text1 };

        // Creating a SimpleAdapter for the AutoCompleteTextView
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);

        // Setting the adapter

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
How to&Answers:

I just experimented with some search results:


The URL encode may not be properly encoding the space. If you have something like “123+” in the get it should produce valid result as you see above. Instead you need to do a replace to swap spaces for +’s instead.

input=input.replace(" ","+");

Try that after your URLEncoder to keep the encoding in but remove any risk of the + being encoded.



Try adding





Try “.” instead of space . You should replace space with dot(.) , If its not working You should try “\ ” as in ubuntu. May be useful


try by replace this line

        input = "input=" + URLEncoder.encode(place[0], "utf-8");


        input = "input=" + URLEncoder.encode(place[0]);


I fond a solution there is nothing wrong with TextWatcher().

need to use below code
In below code I didn’t override “performFiltering” method I added it and my auto complete text box now working fine.

public class CustomAutoCompleteView extends AutoCompleteTextView {

public CustomAutoCompleteView(Context context) {  
    // TODO Auto-generated constructor stub  

public CustomAutoCompleteView(Context context, AttributeSet attrs) {  
    super(context, attrs);  
    // TODO Auto-generated constructor stub  

public CustomAutoCompleteView(Context context, AttributeSet attrs,  
        int defStyle) {  
    super(context, attrs, defStyle);  
    // TODO Auto-generated constructor stub  

protected void performFiltering(final CharSequence text, final int keyCode) {  
    String filterText = "";  
    super.performFiltering(filterText, keyCode);  
* After a selection, capture the new value and append to the existing 
* text 
protected void replaceText(final CharSequence text) {