Autocompletetextview With Google Places Shown In Listview Just Like Uber
Solution 1:
You can achieve this exactly by using EditText
and ListView
, and not AutoCompleteTextView
. Characters are entered in the EditText
on the basis of which the results in the ListView
are filtered by calling the GooglePlacesAutomplete
webservice. The following is the code:
This is your layoout file ( EditText
with ListView
)
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffffff"tools:context="com.example.siddarthshikhar.liftsharesample.EnterLocationActivity"><EditTextandroid:paddingLeft="@dimen/activity_horizontal_margin"android:layout_width="250dp"android:layout_height="35dp"android:textColorHint="#ffffff"android:id="@+id/edEnterLocation"android:textColor="#ffffff"android:textSize="@dimen/abc_text_size_medium_material"android:layout_alignParentLeft="true"android:backgroundTint="#00000000"android:gravity="start|center"><requestFocus /></EditText><ListViewandroid:id="@+id/listView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/filterLayout"/></RelativeLayout>
In your corresponding Activity, access this EditText and apply Filterable. You have to use GooglePlacesAutompleteAdapter
for this.
The following is the GooglePlacesAutompleteAdapter
:
publicclassGooglePlacesAutocompleteAdapterextendsArrayAdapterimplementsFilterable {
privatestaticfinalStringLOG_TAG="Google Places Autocomplete";
privatestaticfinalStringPLACES_API_BASE="https://maps.googleapis.com/maps/api/place";
privatestaticfinalStringTYPE_AUTOCOMPLETE="/autocomplete";
privatestaticfinalStringOUT_JSON="/json";
privatestaticfinalStringAPI_KEY="your_api_key";
private ArrayList<String> resultList;
privateContextcontext=null;
publicGooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.context = context;
}
@OverridepublicintgetCount() {
if(resultList != null)
return resultList.size();
elsereturn0;
}
@Overridepublic String getItem(int index) {
return resultList.get(index);
}
public ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
ArrayList<String> descriptionList = null;
HttpURLConnectionconn=null;
StringBuilderjsonResults=newStringBuilder();
try {
StringBuildersb=newStringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&components=country:in");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URLurl=newURL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReaderin=newInputStreamReader(conn.getInputStream());
// Load the results into a StringBuilderint read;
char[] buff = newchar[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
Log.d("yo",jsonResults.toString());
JSONObjectjsonObj=newJSONObject(jsonResults.toString());
JSONArraypredsJsonArray= jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = newArrayList(predsJsonArray.length());
descriptionList = newArrayList(predsJsonArray.length());
for (inti=0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).toString());
descriptionList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
saveArray(resultList.toArray(newString[resultList.size()]), "predictionsArray", getContext());
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return descriptionList;
}
@Overridepublic Filter getFilter() {
Filterfilter=newFilter() {
@Overrideprotected FilterResults performFiltering(CharSequence constraint) {
FilterResultsfilterResults=newFilterResults();
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;
}
@OverrideprotectedvoidpublishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
setImageVisibility();
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
Access the adapter and apply getFilter()
to the EditText
in the corresponding Activity
. The following is to be added in your Activity corresponding to your layout created earlier:
dataAdapter = new GooglePlacesAutocompleteAdapter(EnterLocationActivity.this, R.layout.adapter_google_places_autocomplete){
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
etEnterLocation.addTextChangedListener(new TextWatcher() {
publicvoidafterTextChanged(Editable s) {
}
publicvoidbeforeTextChanged(CharSequence s, int start, int count, int after) {
}
publicvoidonTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
This should get you going. You can modify your layout as you want. This basically loads the autocomplete data in a ListView
.
Solution 2:
You can achieve automcomplete textview in a simpler way by adding the below code to your layout
<fragment
android:id="@+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
For using the above code you need to configure few settings for your application in Google develepor console .Please refer Android Places autocomplete example for complete example
Post a Comment for "Autocompletetextview With Google Places Shown In Listview Just Like Uber"