android how to make AutoCompleteTextView work as google search box
In my 开发者_Python百科application I have an Activity which extends MapActivity
. and there i put an AutoCompleteTextView
and a button called "Search" so what i write within AutoCompleteTextView
AND press Search button it goes to that location in Google map. AutoCompleteTextView
is for small no of items which i mention in strings.xml.
But I want it should be worked as google search engine, like in google search box whatever we start to write it auto completes every word there.
Thing is that it takes data from google server. Is not it?
If it is, then how can i bind data to my AutoCompleteTextView from Google server so that it works as Google search box.
I am using android API v2.2.
You have to use Google Places API ,you need to generate a place API key first ,check this page :
http://code.google.com/apis/maps/documentation/places/
In my case i have used this code :
final ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,R.layout.list_item);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) { if (count%3 == 1) { adapter.clear(); try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="+ URLEncoder.encode(s.toString(), "UTF-8")
+"&types=geocode&language=fr&sensor=true&key=<getyourAPIkey>");
URLConnection tc = googlePlaces.openConnection();
Log.d("GottaGo", URLEncoder.encode(s.toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
while ((line = in.readLine()) != null) {
sb.append(line);
}
JSONObject predictions = new JSONObject(sb.toString());
JSONArray ja = new JSONArray(predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
adapter.add(jo.getString("description"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
} });
AutoCompleteTextView with google search Api
your xml
<AutoCompleteTextView
android:id="@+id/main_omnibox_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@null"
android:hint="Search"
android:focusable="true"
android:focusableInTouchMode="true"
android:selectAllOnFocus="true"
android:singleLine="true"
android:textSize="@dimen/_14sdp" />
Activity.java
this.inputBox = (AutoCompleteTextView) findViewById(R.id.main_omnibox_input);
inputBox.setAdapter(new SearchAutocompleteAdapter(SearchActivity.this, new
SearchAutocompleteAdapter.OnSearchCommitListener() {
@Override
public void onSearchCommit(String text) {
inputBox.setText(text);
inputBox.setSelection(text.length());
}
}));
this.inputBox.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
String charSequence = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
inputBox.setText(Html.fromHtml(BrowserUnit.urlWrapper(charSequence)), BufferType.SPANNABLE);
inputBox.setSelection(charSequence.length());
// your code
// updateAlbum(charSequence);
// hideSoftInput(SearchActivity.this.inputBox);
}
});
SearchAdapter looks like
public class SearchAutocompleteAdapter extends BaseAdapter implements Filterable {
interface OnSearchCommitListener {
void onSearchCommit(String text);
}
private final Context mContext;
private final OnSearchCommitListener commitListener;
private List<String> completions = new ArrayList<>();
static final String searchCompleteUrl = "https://www.google.com/complete/search?client=firefox&q=%s";
SearchAutocompleteAdapter(Context context, OnSearchCommitListener commitListener) {
mContext = context;
this.commitListener = commitListener;
}
@Override
public int getCount() {
return completions.size();
}
@Override
public Object getItem(int position) {
return completions.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint("ClickableViewAccessibility")
@Override
@SuppressWarnings("ConstantConditions")
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
}
TextView textview = convertView.findViewById(android.R.id.text1);
textview.setText(completions.get(position));
Drawable d = ContextCompat.getDrawable(mContext, R.drawable.icon_goarrowsmall);
final int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, mContext.getResources().getDisplayMetrics());
d.setBounds(0, 0, size, size);
textview.setCompoundDrawables(null, null, d, null);
textview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN) {
return false;
}
TextView t = (TextView) view;
if (event.getX() > t.getWidth() - t.getCompoundPaddingRight()) {
commitListener.onSearchCommit(getItem(position).toString());
return true;
}
return false;
}
});
parent.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getX() > view.getWidth() - size * 2) {
return true;
}
return false;
}
});
return convertView;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
// Invoked on a worker thread
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<String> results = getCompletions(constraint.toString());
filterResults.values = results;
filterResults.count = results.size();
}
return filterResults;
}
@Override
@SuppressWarnings("unchecked")
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
completions = (List<String>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
}
private List<String> getCompletions(String text) {
int total = 0;
byte[] data = new byte[16384];
try {
URL url = new URL(URLUtil.composeSearchUrl(text, searchCompleteUrl, "%s"));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
while (total <= data.length) {
int count = in.read(data, total, data.length - total);
if (count == -1) {
break;
}
total += count;
}
if (total == data.length) {
// overflow
return new ArrayList<>();
}
} finally {
urlConnection.disconnect();
}
} catch (IOException e) {
return new ArrayList<>();
}
JSONArray jsonArray;
try {
jsonArray = new JSONArray(new String(data, StandardCharsets.UTF_8));
} catch (JSONException e) {
return new ArrayList<>();
}
jsonArray = jsonArray.optJSONArray(1);
if (jsonArray == null) {
return new ArrayList<>();
}
final int MAX_RESULTS = 10;
List<String> result = new ArrayList<>(Math.min(jsonArray.length(), MAX_RESULTS));
for (int i = 0; i < jsonArray.length() && result.size() < MAX_RESULTS; i++) {
String s = jsonArray.optString(i);
if (s != null && !s.isEmpty()) {
result.add(s);
}
}
return result;
}
}
精彩评论