Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在ActionBar中将AutoCompleteTextView改为SearchView_Android_Google Places Api_Autocompletetextview_Searchview - Fatal编程技术网

Android 在ActionBar中将AutoCompleteTextView改为SearchView

Android 在ActionBar中将AutoCompleteTextView改为SearchView,android,google-places-api,autocompletetextview,searchview,Android,Google Places Api,Autocompletetextview,Searchview,我有一个AutoCompleteTextView,它提供用户从googleplacesapi自动完成搜索结果。完成后,我发现了搜索视图,以及如何将其放置在操作栏中。我查看了google提供的SearchView示例,并将其作为起点添加到我的应用程序中(它列出了已安装的应用程序),但我不知道如何从这里开始。我想拥有与AutoCompleteTextView相同的功能,但改用SearchView。 有什么建议吗? 下面提供了整个课程 import java.io.BufferedReader; im

我有一个AutoCompleteTextView,它提供用户从googleplacesapi自动完成搜索结果。完成后,我发现了搜索视图,以及如何将其放置在操作栏中。我查看了google提供的SearchView示例,并将其作为起点添加到我的应用程序中(它列出了已安装的应用程序),但我不知道如何从这里开始。我想拥有与AutoCompleteTextView相同的功能,但改用SearchView。 有什么建议吗? 下面提供了整个课程

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;



/**
 * 
 * @author 
 *
 */
public class PlacesListSearchActivity extends Activity implements SearchView.OnQueryTextListener{

    private static final String TAG = "PlacesListActivity";

    private ResultReceiver mReceiver;

    private OnSharedPreferenceChangeListener sharedPreferencesListener;
    private SharedPreferences sharedPreferences;

    /** Called when the activity is first created. */
    public ArrayAdapter<String> adapter;
    public AutoCompleteTextView textView;

    private SearchView mSearchView;
    private TextView mStatusView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        setContentView(R.layout.places_search);
        mStatusView = (TextView) findViewById(R.id.status_text);


        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item_list);
        textView = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
        adapter.setNotifyOnChange(true);
        textView.setHint("type store name");
        textView.setAdapter(adapter);
        textView.addTextChangedListener(new TextWatcher() {

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (count%3 == 1) {
                adapter.clear();
                    GetPlaces task = new GetPlaces();
                    //now pass the argument in the textview to the task
                    task.execute(textView.getText().toString());
            }
        }

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

        }

        public void afterTextChanged(Editable s) {

        }

        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.searchview_in_menu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        mSearchView = (SearchView) searchItem.getActionView();
        setupSearchView(searchItem);

        return true;
    }

    private void setupSearchView(MenuItem searchItem) {

        if (isAlwaysExpanded()) {
            mSearchView.setIconifiedByDefault(false);
        } else {
            searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
                    | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
        }

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        if (searchManager != null) {
            List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();

            // Try to use the "applications" global search provider
            SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
            for (SearchableInfo inf : searchables) {
                if (inf.getSuggestAuthority() != null
                        && inf.getSuggestAuthority().startsWith("applications")) {
                    info = inf;
                }
            }
            mSearchView.setSearchableInfo(info);
        }

        mSearchView.setOnQueryTextListener(this);
    }

    public boolean onQueryTextChange(String newText) {
        mStatusView.setText("Query = " + newText);
        return false;
    }

    public boolean onQueryTextSubmit(String query) {
        mStatusView.setText("Query = " + query + " : submitted");
        return false;
    }

    public boolean onClose() {
        mStatusView.setText("Closed!");
        return false;
    }

    protected boolean isAlwaysExpanded() {
        return false;
    }

    class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
        @Override
        // three dots is java for an array of strings
        protected ArrayList<String> doInBackground(String... args)
        {
            Log.d("PlacesListActivity", "doInBackground");
            ArrayList<String> predictionsArr = new ArrayList<String>();
            try
            {
                URL googlePlaces = new URL(
                        "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
                        URLEncoder.encode(args[0], "UTF-8") +
//                      "&types=geocode&language=en&sensor=true&key=" + SEARCHES FOR GEO CODES
                        "&types=establishment&language=en&sensor=true&key=" +
                        getResources().getString(R.string.googleAPIKey));

                Log.d("PlacesListActivity", googlePlaces.toString());

                URLConnection tc = googlePlaces.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        tc.getInputStream()));

                String line;
                StringBuffer sb = new StringBuffer();
                //take Google's legible JSON and turn it into one big string.
                while ((line = in.readLine()) != null) {
                    sb.append(line);
                }
                //turn that string into a JSON object
                JSONObject predictions = new JSONObject(sb.toString()); 
                //now get the JSON array that's inside that object            
                JSONArray ja = new JSONArray(predictions.getString("predictions"));

                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    //add each entry to our array
                    predictionsArr.add(jo.getString("description"));
                }
            } catch (IOException e)
            {
            Log.e("PlacesListActivity", "GetPlaces : doInBackground", e);
            } catch (JSONException e)
            {
            Log.e("PlacesListActivity", "GetPlaces : doInBackground", e);
            }

            return predictionsArr;
        }

        @Override
        protected void onPostExecute(ArrayList<String> result){
            Log.d("PlacesListActivity", "onPostExecute : " + result.size());
            //update the adapter
            adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
            adapter.setNotifyOnChange(true);
            //attach the adapter to textview
            textView.setAdapter(adapter);

            for (String string : result) {
                Log.d("PlacesListActivity", "onPostExecute : result = " + string);
                adapter.add(string);
                adapter.notifyDataSetChanged();
            }

            Log.d("PlacesListActivity", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
        }

    }

}

要在SearchView中获取Places Autocomplete API结果,首先需要API的ContentProvider

import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

public class PlacesSuggestionProvider extends ContentProvider {
    private static final String LOG_TAG = "ExampleApp";

    public static final String AUTHORITY = "com.example.google.places.search_suggestion_provider";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/search");

    // UriMatcher constant for search suggestions
    private static final int SEARCH_SUGGEST = 1;

    private static final UriMatcher uriMatcher;

    private static final String[] SEARCH_SUGGEST_COLUMNS = {
            BaseColumns._ID,
            SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_TEXT_2,
            SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
    };

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
        uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
    }

    @Override
    public int delete(Uri uri, String arg1, String[] arg2) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case SEARCH_SUGGEST:
                return SearchManager.SUGGEST_MIME_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URL " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues arg1) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        Log.d(LOG_TAG, "query = " + uri);

        // Use the UriMatcher to see what kind of query we have
        switch (uriMatcher.match(uri)) {
            case SEARCH_SUGGEST:
                Log.d(LOG_TAG, "Search suggestions requested.");
                MatrixCursor cursor = new MatrixCursor(SEARCH_SUGGEST_COLUMNS, 1);
                cursor.addRow(new String[] {
                        "1", "Search Result", "Search Result Description", "content_id"
                });
                return cursor;
            default:
                throw new IllegalArgumentException("Unknown Uri: " + uri);
        }
    }

    @Override
    public int update(Uri uri, ContentValues arg1, String arg2, String[] arg3) {
        throw new UnsupportedOperationException();
    }
}
然后将Places Autocomplete API客户端代码添加到内容提供者的查询方法中。您可以按如下方式提取用户输入:

String query = uri.getLastPathSegment().toLowerCase();
将PlacesSuggestionProvider添加到您的AndroidManifest中,并确保您的活动具有可搜索的配置

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <activity android:name=".PlacesSearchViewActivity" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

        <provider
            android:name="com.example.google.places.PlacesSuggestionProvider"
            android:authorities="com.example.google.places.search_suggestion_provider"
            android:syncable="false" />
    </application>

</manifest>
一些关键文档包括:

添加自定义建议:

创建内容提供商:

使用搜索小部件:

使用谷歌搜索Api自动完成文本视图

您的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" />

您的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);
        }
    });
this.inputBox=(AutoCompleteTextView)findViewById(R.id.main\u omnibox\u input);
setAdapter(新的SearchAutocompleteAdapter(SearchActivity.this,新的SearchAutocompleteAdapter.OnSearchCommitListener)(){
@凌驾
公共void onSearchCommit(字符串文本){
inputBox.setText(文本);
inputBox.setSelection(text.length());
}
}));
this.inputBox.setOnItemClickListener(新的OnItemClickListener(){
public void onItemClick(AdapterView AdapterView,View视图,int i,long j){
String charSequence=((TextView)view.findviewbyd(android.R.id.text1)).getText().toString();
inputBox.setText(Html.fromHtml(BrowserUnit.urlWrapper(charSequence)),BufferType.Spanable);
inputBox.setSelection(charSequence.length());
//你的代码
//updateAlbum(charSequence);
//hideSoftInput(SearchActivity.this.inputBox);
}
});
搜索自动完成适配器

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;
}
公共类SearchAutocompleteAdapter扩展BaseAdapter实现可过滤{
SearchCommitListener上的接口{
void onSearchCommit(字符串文本);
}
私有最终上下文mContext;
私人最终搜索提交人提交人;
私有列表完成=新建ArrayList();
静态最终字符串searchCompleteUrl=”https://www.google.com/complete/search?client=firefox&q=%s";
SearchAutocompleteAdapter(上下文上下文,OnSearchCommitListener commitListener){
mContext=上下文;
this.commitListener=commitListener;
}
@凌驾
public int getCount(){
返回completions.size();
}
@凌驾
公共对象getItem(int位置){
返回完成。获取(位置);
}
@凌驾
公共长getItemId(int位置){
返回位置;
}
@SuppressLint(“ClickableViewAccessibility”)
@凌驾
@抑制警告(“恒定条件”)
公共视图getView(最终整数位置、视图转换视图、视图组父视图){
if(convertView==null){
LayoutInflater充气器=(LayoutInflater)mContext.getSystemService(Context.LAYOUT\u充气器\u服务);
convertView=充气机。充气(android.R.layout.simple\u下拉列表\u item\u 1line,父项,false);
}
TextView TextView=convertView.findViewById(android.R.id.text1);
setText(completions.get(position));
Drawable d=ContextCompat.getDrawable(mContext,R.Drawable.icon\u goarrowsmall);
最终整数大小=(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,32,mContext.getResources().getDisplayMetrics());
d、 立根(0,0,大小,大小);
setCompoundDrawables(null,null,d,null);
textview.setOnTouchListener(新视图.OnTouchListener(){
@凌驾
公共布尔onTouch(视图、运动事件){
if(event.getAction()!=MotionEvent.ACTION\u向下){
返回false;
}
TextView t=(TextView)视图;
if(event.getX()>t.getWidth()-t.getCompoundPaddingRight()){
onSearchCommit(getItem(position.toString());
返回true;
}
返回false;
}
});
父.setOnTouchListener(新视图.OnTouchListener(){
@凌驾
公共布尔onTouch(视图、运动事件){
if(event.getX()>view.getWidth()-size*2){
返回true;
}
返回false;
}
});
返回视图;
}
@凌驾
公共过滤器getFilter(){
返回新筛选器(){
@凌驾
受保护的筛选器结果性能筛选(CharSequence约束){
//在工作线程上调用
FilterResults FilterResults=新的FilterResults();
if(约束!=null){
列表结果=getCompletions(constraint.toString());
filterResults.values=结果;
filterResults.count=结果.size();
}
返回过滤器结果;
}
@凌驾
@抑制警告(“未选中”)
受保护的void publishResults(CharSequence约束、FilterResults结果){
if(results!=null&&results.count>0){
完成=(列表)results.values;
notifyDataSetChanged();
}否则{
notifyDataSetionValidated();
}
}
};
}
私有列表getCompletions(字符串文本){
int-total=0;
字节[]数据=新字节[16384];
试一试{
URL URL=新URL(URLUtil.composeSearchUrl(文本,searchCompleteUrl,“%s”);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
试一试{
InputStream in=新的缓冲区EDI
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

public class PlacesSuggestionProvider extends ContentProvider {
    private static final String LOG_TAG = "ExampleApp";

    public static final String AUTHORITY = "com.example.google.places.search_suggestion_provider";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/search");

    // UriMatcher constant for search suggestions
    private static final int SEARCH_SUGGEST = 1;

    private static final UriMatcher uriMatcher;

    private static final String[] SEARCH_SUGGEST_COLUMNS = {
            BaseColumns._ID,
            SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_TEXT_2,
            SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
    };

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
        uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
    }

    @Override
    public int delete(Uri uri, String arg1, String[] arg2) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case SEARCH_SUGGEST:
                return SearchManager.SUGGEST_MIME_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URL " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues arg1) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        Log.d(LOG_TAG, "query = " + uri);

        // Use the UriMatcher to see what kind of query we have
        switch (uriMatcher.match(uri)) {
            case SEARCH_SUGGEST:
                Log.d(LOG_TAG, "Search suggestions requested.");
                MatrixCursor cursor = new MatrixCursor(SEARCH_SUGGEST_COLUMNS, 1);
                cursor.addRow(new String[] {
                        "1", "Search Result", "Search Result Description", "content_id"
                });
                return cursor;
            default:
                throw new IllegalArgumentException("Unknown Uri: " + uri);
        }
    }

    @Override
    public int update(Uri uri, ContentValues arg1, String arg2, String[] arg3) {
        throw new UnsupportedOperationException();
    }
}
String query = uri.getLastPathSegment().toLowerCase();
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >

        <activity android:name=".PlacesSearchViewActivity" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

        <provider
            android:name="com.example.google.places.PlacesSuggestionProvider"
            android:authorities="com.example.google.places.search_suggestion_provider"
            android:syncable="false" />
    </application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="@string/search_hint"
    android:searchSuggestAuthority="com.example.google.places.search_suggestion_provider">
</searchable>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_search"
          android:title="@string/menu_search"
          android:icon="@drawable/ic_menu_search"
          android:showAsAction="collapseActionView|ifRoom"
          android:actionViewClass="android.widget.SearchView" />
</menu>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the options menu from XML
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    // Tells your app's SearchView to use this activity's searchable configuration
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default

    return true;
}
  <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" />
  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);
        }
    });
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;
}