Ajeet Singh
Ajeet Singh

Reputation: 2009

Pre-populate address in PlaceAutocomplete (Google Api)

I have implemented PlaceAutocomplete in my android project everything is working fine, but as per its working when call this(PlaceAutocomplete) activity is appear empty

enter image description here

Using this code to start Code:

Intent intent =new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).build(getActivity());
startActivityForResult(intent, 0);

But as per My project requirement I need to pre-populate the previously selected address here(e.g. i have selected any address in first time and set that address into any Text Field, now user want to edit that address but if user click on the text view auto complete appears empty).

I have tried a lot but did not find any solution.
It there any way to achieve that in android???

Upvotes: 4

Views: 2731

Answers (3)

Parth Patel
Parth Patel

Reputation: 891

This is working for me.

implementation 'com.google.android.libraries.places:places:2.3.0'

For Intent

List<Place.Field> fields = Arrays.asList(
            Place.Field.ID,
            Place.Field.NAME,
            Place.Field.ADDRESS,
            Place.Field.LAT_LNG);
    // Start the autocomplete intent.
    Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields)
            .setInitialQuery(addressTexts)
            .build(getActivity());
    startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

Now it has .setInitialQuery(<your address texts>) method for initial query.

Upvotes: 0

Ajeet Singh
Ajeet Singh

Reputation: 2009

Found It.

I was expecting that answer earlier.

There is method in PlaceAutocomplete.IntentBuilder class i.e. zzfd(@Nullable String var1).

It need a String value(your address if you want to prepopulate). So you can use this while calling startActivityForResult().

Code Will be Like:

Intent intent =new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                    .zzfd(your_text_View.getText().toString())
                                    .build(getActivity());
startActivityForResult(intent, 1);

You can pass null in zzfd() if you do not have address in starting.

You send address also on "initial_query" KEY, that will also work same.

For example:

Intent intent =new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                   .build(getActivity());
if (!TextUtils.isEmpty(your_text_View.getText().toString())) {
intent.putExtra("initial_query", (your_text_View.getText().toString());
} else {
   intent.removeExtra("initial_query");
}
startActivityForResult(intent, 1);

Upvotes: 4

aA_neal
aA_neal

Reputation: 21

Creating a custom auto complete text view for places:

XML:

<AutoCompleteTextView
                    android:id="@+id/location_Et"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_toStartOf="@+id/textCancel"
                    android:background="@drawable/search_box_bg"
                    android:drawablePadding="8dp"
                    android:drawableStart="@drawable/ic_search_grey_700_24dp"
                    android:ellipsize="end"
                    android:focusableInTouchMode="true"
                    android:hint="Search Location"
                    android:imeOptions="actionSearch"
                    android:inputType="textNoSuggestions"
                    android:lines="1"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:textColor="@color/standard_gray"
                    android:textCursorDrawable="@null"
                    android:textSize="18sp"
                    app:fontFileName="ProximaNova-Regular.otf"/>

In Activity:

locationEt = (AutoCompleteTextView) findViewById(R.id.location_Et);

        final PlacesAutoCompleteAdapter adapterPopUpDestination = new PlacesAutoCompleteAdapter(CustomLocationSelectionActivity.this, R.layout.autocomplete_list_text);
        locationEt.setAdapter(adapterPopUpDestination);

        locationEt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String address = adapterPopUpDestination.getItem(i);

            }
        });

Adapter:

public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
    public static final String LOG_TAG = "ImpactForce";
    String textaddress;
    private ArrayList<String> resultList = new ArrayList<String>();
    private LayoutInflater inflater;
    private ViewHolder holder;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent);
    }

    private View getMyView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.autocomplete_list_text, parent, false);
            holder = new ViewHolder();

            holder.addressTitle = (TextView) convertView.findViewById(R.id.textViewTitleHeader);
            holder.address = (TextView) convertView.findViewById(R.id.textViewTitleSub);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        try {
            String address = getItem(position);

            String add[] = address.split(",");

            holder.addressTitle.setText(add[0]);
            holder.address.setText(address);
        } catch (Exception e) {
        }
        return convertView;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getMyView(position, convertView, parent);
    }

    @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.
                    if (Utility.isOnline(getContext())) {
                        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;
    }

    private ArrayList<String> autocomplete(String input) {

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            //https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Paris&types=geocode&key=YOUR_API_KEY
            StringBuilder sb = new StringBuilder(NetworkConstant.PLACES_API_BASE
                                                         + NetworkConstant.TYPE_AUTOCOMPLETE + NetworkConstant.OUT_JSON);
            //sb.append("&types=geocode&key=" + Constant.PLACES_AUTOCOMPLETE_API_KEY);
            sb.append("?sensor=false&key=" + NetworkConstant.PLACES_AUTOCOMPLETE_API_KEY);

            // sb.append("&location=" + BeanLocation.getLocation().getLatitude()
            // + "," + BeanLocation.getLocation().getLongitude());
            sb.append("&radius=500");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));
            Log.w("url data", "" + sb.toString());
            // AppLog.Log("PlaceAdapter", "Place Url : " + sb.toString());
            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            Log.w("url data", "" + sb.toString());
            // 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
            // System.out.println(jsonResults.toString());
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultList.clear();
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString(
                        "description"));
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }

    public class ViewHolder {

        TextView address;
        TextView addressTitle;
    }

Upvotes: 1

Related Questions