Searchable Activity is not called - android

I am trying to implement WhatsApp like Search in my application.I have to implement the following screen :
As you can see in the screenshot,I have a search icon as option menu .
XML:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#drawable/search"
android:orderInCategory="100"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
</menu>
On clicking search icon search view will be opened .
CODE:
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_friend_list_activity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search button clicked", Toast.LENGTH_SHORT).show();
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) FriendsListActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (item != null) {
searchView = (SearchView) item.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(FriendsListActivity.this.getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Log.e("Query",query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<activity
android:name=".activity.FriendsListActivity"
android:parentActivityName=".activity.WelcomeActivity">
<!-- To display the search view-->
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<activity android:name=".activity.SearchResultsActivity">
<intent-filter>
<action
android:name="android.intent.action.SEARCH"
android:launchMode="singleTop" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
You can see here i have searchable activity named SearchResultsActivity.
I am following this tutorial.
SearchResultsACtivity:
public class SearchResultsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.e("onCreate","in SerachActivity called");
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Log.e("Query1",query);
//use the query to search your data somehow
}
}
}
I think i am doing something wrong here.When i am trying to search ,SearchResultsActivity is not called .Please help me how can i implement search as WhatsApp do?

I guess you're reading the android tutorial here, that page is very confusing if not completely wrong. There're two places went wrong in your code.
When you call searchView#setSearchableInfo, you're telling Android what activity to launch to handle search result, in your case SearchResultsActivity. So you can't set component name to FriendsListActivity, instead change it to SearchResultsActivity.searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultsActivity.class)))
In order for an activity to become a searchable that's able to be found by searchManager, you need to add the android.app.searchable meta-data label to the Activity block in your manifest. Note this label should NOT be added to the activity you display the SearchView, the tutorial page totally states it wrong. So change your SearchResultsActivity to the following.
If you made these two changes, your SearchView from FriendsListActivity would correctly holds a mSearchable instance that's able to start SearchResultsAcitivity. Otherwise it will be null.
<activity android:name=".activity.SearchResultsActivity">
<intent-filter>
<action
android:name="android.intent.action.SEARCH"
android:launchMode="singleTop" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"/>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>

You have wrote like this: (so you passed FriendsListActivity instead of SearchResult Activity):
searchView.setSearchableInfo(searchManager.getSearchableInfo(FriendsListActivity.this.getComponentName()));
but you should pass the componentName like this:
ComponentName componentName = new ComponentName(FriendsListActivity.this , SearchResultsActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));

Related

Start new activity from SearchView

I have 2 activities: the first has a action bar with a search view, the second should display the results of the search query.
androidmanifest:
<activity
android:name=".SearchActivity"
...
android:launchMode="singleTop">
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
...
</activity>
<activity
android:name=".ResultsActivity"
...
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
searchable.xml
<searchable
xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/enter_a_word" />
SearchActivity
....
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_noun_list, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()));
return true;
}
....
ResultsActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
}
...
}
the problem is that after a query is entered into the searchview, nothing happens. No errors, nothing. How can i open the resultsactivity after the query is entered in the searchactivity?
This answer is a little late but I feel it'll be useful for future viewers. The dilemma seems to come from the ambiguity of the Android SearchView tutorial. The scenario they cover assumes you will be displaying the results in the same Activity the SearchView resides. In such a scenario, the Activity tag in the AndroidManifest.xml file would look something like this:
<activity
android:name=".MainActivity"
android:label="#string/main_activity_label"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Then, to handle the results in the same Activity, you would Override the onNewIntent method:
#Override
public void onNewIntent(Intent intent){
setIntent(intent);
if(Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//now you can display the results
}
}
However, in a situation where we want to display the results in another Activity, we must put the Intent Filter and meta tag into the results Activity and introduce a new meta tag for the SearchView Activity. So, our Activities will look something like this in the AndroidManifest.xml file:
<activity
android:name=".MainActivity"
android:label="#string/main_activity_label"
android:launchMode="singleTop">
<!-- meta tag points to the activity which displays the results -->
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
</activity>
<activity
android:name=".SearchResultsActivity"
android:label="#string/results_activity_label"
android:parentActivityName="com.example.MainActivity">
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity" />
<!-- meta tag and intent filter go into results activity -->
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
Then, in our MainActivity's onCreateOptionsMenu method, activate the SearchView (assumes you're adding the SearchView to the ActionBar). Rather than using getComponentName() in the SearchManager's getSearchableInfo() method call, we instantiate a new ComponentName object using the MainActivity's context and the SearchResultsActivity class:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_home, menu);
SearchView search = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultsActivity.class)));
search.setQueryHint(getResources().getString(R.string.search_hint));
return true;
}
Finally, in our SearchResultsActivity class, in the onCreate method, we can handle the search results:
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
Don't forget to create the searchable.xml resource file and add the SearchView to your layout.
searchable.xml (res/xml/searchable.xml; create xml folder under res if needed):
<?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:voiceSearchMode="showVoiceSearchButton|launchRecognizer"/>
Layout (example of adding the SearchView to ActionBar as a menu item):
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.MainActivity">
<group android:checkableBehavior="single">
<item android:id="#+id/action_search" android:title="Search"
android:orderInCategory="1" app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</group>
</menu>
Resources:
Display Results In Same Activity
Display Results In Different Activity
ComponentName
I understood the problem i had also faced the same, This is happening because you are passing the current component name by passing the
getComponentName()
This will be initialize by the current activity name so you need to initialize it with the searchable activity name in given below format and pass the same Component instance it starts the new activity.
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultsActivity.class)));
search.setQueryHint(getResources().getString(R.string.search_hint));
Hope it I have answered the Question!
Without seeing your activity code, I would suggest you try this approach - also assuming you have all the files created as stated above;
In your results activity,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.core_actions, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setOnQueryTextListener(this);
return true;
}
Remember that this is the activity that has your data that you want to make searchable:
You must implement the SearchView.OnQueryTextListener interface in the same activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
ProductsResulstActivity.this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
productFilterAdapter.getFilter().filter(newText);
if (TextUtils.isEmpty(newText)) {
listView.clearTextFilter();
}
else {
listView.setFilterText(newText);
}
return true;
}
productFilterAdapter is the adapter that you must create beforehand.
It should implement Filterable interface. I hope this helps.
If you need further assistance, please let me know. Good luck

How to open a new activity to show results from a SearchView?

I've been working in an application that uses a SearchView Widget as an ActionView in the ActionBar.
The problem occurs when I type a search and hit the search button, it opens the same activity, what I want to do is to open a new Activity and show the results on a ListView, how can this be fixed?
This is my AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="andres.hotelsoria" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher_hotel"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<activity
android:name=".SearchableActivity"
android:label="#string/title_activity_searchable" >
</activity>
</application>
You can start a new activity by attaching a OnQueryTextListener to the SearchView.
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent intent = new Intent(getApplicationContext(), SearchableActivity.Class);
startActivity(intent);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
read this post
http://developer.android.com/guide/topics/search/index.html
as mentioned in this document follow these steps
1)Create a folder in res->xml->searchable.xml paste content as mention in documentation
2)Go to AndroidManifest.xml and change Activity(where you want to deliver result for search) to this
<activity android:name=".SearchableActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
3)Declare the SearchView in menu.xml file as
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="your activity context" >
<item
android:id="#+id/mi_search"
android:title="#string/search"
android:orderInCategory="2"
android:icon="#drawable/searchicon"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
4)in onCreateOptionsMenu(Menu menu) do this code
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget;
5)in onOptionsItemSelected.
->fetch Id of search view
->simple paste onSearchRequested() inside block
public boolean onSearchRequested() {
return super.onSearchRequested();
}
6)register searchView with onQueryTextListener and do what you want to do
http://developer.android.com/reference/android/widget/SearchView.OnQueryTextListener.html
//You hav to start the new activity like this
SearchView.OnQueryTextListener textListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
//use intent here to start new activity and pass "query" string.
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
};
searchView.setOnQueryTextListener(textListener);

SearchView in ActionBarSherlock

I'm using the SearchView widget in ActionbarSherlock as a follows:
File.java
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.MenuSearch).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setSubmitButtonEnabled(true);
return true;
}
File.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/MenuSearch" android:title="#string/Bs"
android:icon="#drawable/ic_action_search"
android:showAsAction="always|withText"
android:actionViewClass="com.actionbarsherlock.widget.SearchView" >
</item>
</menu>
In my application I get to show the search icon and select it unfolds the search box for the widget, but when I write any search I do not know how to interact with the widget SearchView to launch a new activity and show a series of results.
With the command searchView.setSubmitButtonEnabled(true); appears a icon similar to 'play' and I suppose it is for just that, but I do not know how to interact with it.
Can anyone help?
Official android documentation here describes how start new activity to handle search query and display results.
First you need to create (if you havent already) searchable configuration in res/xml/searchable.xml, like this:
<?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" />
Set this configuration for your activity, that contains SearchView in actionbar, like this (in manifest):
<activity ... >
...
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
So basically, you need your searchable activity (new activity that will start after submitting search query) to handle the android.intent.action.SEARCH action. Declare it in manifest like this:
<activity android:name=".SearchResultsActivity" ... >
...
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
...
</activity>
And your searchable activity should look like this:
public class SearchResultsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
...
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
...
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
...
}

Android Search Activity in Single Activity

I am trying to make my app consist a SINGLE activity. This activity should be able to create a search and also receive a search. Unfortunately, I am getting a "double" search bar in my SearchView when I click on the search button in the action bar. I mean that there is a search bar (dark-- SearchView) that appears for a second in the action bar, and then a second one (white) appears OVER the action bar. Any help? What am I doing wrong?
Sorry, this search thing is all new and confusing to me.
MainActivity (the only activity):
public class MainActivity extends ActionBarActivity {
Menu mMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getSupportActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.activity_main);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
mMenu = menu;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
default:
return false;
}
}
#SuppressLint("NewApi")
#Override
public boolean onSearchRequested() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
MenuItem mi = mMenu.findItem(R.id.search);
if(mi.isActionViewExpanded()){
mi.collapseActionView();
} else{
mi.expandActionView();
}
} else{
//onOptionsItemSelected(mMenu.findItem(R.id.search));
}
return super.onSearchRequested();
}
}
main.xml (the menu xml):
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.brianco.andypedia="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/search"
android:title="#string/action_settings"
android:icon="#drawable/ic_launcher"
android:actionProviderClass="android.support.v7.widget.ShareActionProvider"
com.brianco.andypedia:showAsAction="always|collapseActionView"
com.brianco.andypedia:actionViewClass="android.support.v7.widget.SearchView" />
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
</menu>
searchable.xml:
<?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:voiceSearchMode="showVoiceSearchButton|launchRecognizer" />
in the manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar" >
<activity
android:name="com.brianco.andypedia.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable" android:resource="#xml/searchable" />
</activity>
<meta-data android:name="android.app.default_searchable"
android:value=".MainActivity" />
From Setting Up the Search Interface in the Android Documentation:
In your searchable activity, handle the ACTION_SEARCH intent by
checking for it in your onCreate() method.
Note: If your searchable activity launches in single top mode
(android:launchMode="singleTop"), also handle the ACTION_SEARCH intent
in the onNewIntent() method. In single top mode, only one instance of
your activity is created and subsequent calls to start your activity
do not create a new activity on the stack. This launch mode is useful
so users can perform searches from the same activity without creating
a new activity instance every time.
Please try to add the following attribute to your <activity> in your manifest file:
android:launchMode="singleTop"
This will make the same activity to receive the search intent.
More info here: http://developer.android.com/guide/topics/manifest/activity-element.html
Also, you have <intent-filter> declared twice, you should merge it into one element.
Okay, the problem had to do with calling onSearchRequested() in onOptionsItemSelected(MenuItem item). That is redundant when I have a SearchView and should only be called on older platforms.
So, I created a separate menu item for devices under Honeycomb. It is removed at runtime for newer devices. The SearchView is removed at runtime for older devices.
See updated code below:
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
mMenu = menu;
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//remove old
menu.removeItem(R.id.search_old);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
} else{
//remove new
menu.removeItem(R.id.search);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_old:
onSearchRequested();
return true;
default:
return false;
}
}
#SuppressLint("NewApi")
#Override
public boolean onSearchRequested() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
MenuItem mi = mMenu.findItem(R.id.search);
if(mi.isActionViewExpanded()){
mi.collapseActionView();
} else{
mi.expandActionView();
}
} else{
//onOptionsItemSelected(mMenu.findItem(R.id.search));
}
return super.onSearchRequested();
}
THANKS,
This has worked for me.
Manifest:
<activity
android:name=".Buscar"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_buscar"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Activity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
query = intent.getStringExtra(SearchManager.QUERY);
mysearch(query);
}

Set search hint dynamically

Does anybody knows how to set android search dialog hint dynamically?
T have try to do something like:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/search_label"
android:hint="#string/search_hint"
android:id="#+id/search_dialog_text">
</searchable>
Somewhere:
#Override
public boolean onSearchRequested() {
Bundle appSearchData = new Bundle();
appSearchData.putString("SomeSpecificParam", SomeClass.class.getName());
startSearch("", false, appSearchData, false);
EditText text = (EditText )findViewById(R.id.search_dialog_text);
text.setHint("Search something else");
return true;
}
but text is equal null.
So looking forward you suggestions. Thanks.
This feels pretty hacky but worked for me - not truly dynamic but worked for alternating between the two search hints I needed:
I created a second searchable.xml (as described in the Android search docs), called searchable2.xml, with my second search hint defined.
I created a dummy activity extended from my original activity and overriding nothing.
In the manifest the dummy activity was associated with the new searchable2.xml:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<activity android:name=".DummyActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable2"/>
</activity>
In 'MainActivity' I overrode 'onSearchRequested()' to reference the appropriate searchable activity:
public boolean onSearchRequested()
{
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
if(searchManager!=null)
{
// start the search with the appropriate searchable activity
// so we get the correct search hint in the search dialog
if(/* your condition here */)
searchManager.startSearch(null, false,new ComponentName(this, MainActivity.class), null, false);
else
searchManager.startSearch(null, false,new ComponentName(this, DummyActivity.class), null, false);
return true;
}
return false;
}
Nasty. But desperate times call for desperate measures...
AFAIK, and from looking at the Android source the class is only used to look up the metadata, but if anybody knows differently then please let me know.
They've added a note at http://developer.android.com/guide/topics/search/search-dialog.html#SearchableConfiguration stating that
Note: The system uses this file to instantiate a SearchableInfo object, but you cannot create this object yourself at runtime—you must declare the searchable configuration in XML.
So it seems that the answer to your question is that you cannot set the search dialog hint dynamically.
I managed to do this with ABS using the OnActionExpandListener and a custom actionView, e.g.:
menu.add("Search")
.setActionView(R.layout.collapsible_edittext)
.setOnActionExpandListener(new MenuItem.OnActionExpandListener()
{
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
((EditText) item.getActionView()).setHint("Your custom text here");
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
});
with collapsible_edittext.xml:
<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#color/search_fg"
android:background="#drawable/textfield_default_holo_light"
android:hint="[will be replaced at runtime]"/>
If you are using the Toolbar and SearchView widgets, you can easily set the search query hint by calling:
SearchView.setQueryHint(CharSequence hint)
It looks like you're almost there.
The SearchDialog source does this to get the auto complete editable.
mSearchAutoComplete = (SearchAutoComplete) findViewById(com.android.internal.R.id.search_src_text);
(note that the SearchAutoComplete class is a subclass of AutoCompleteTextView)
There is a much simpler answer than any of the above. It loads the default searchable.xml for your activity, and then uses java reflection to update the private mHintId field inside the SearchableInfo instance:
#Override
public void onPrepareOptionsMenu(Menu menu) {
SearchManager searchManager = (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchableInfo si = searchManager.getSearchableInfo( getActivity().getComponentName() );
try {
Field mHintId = si.getClass().getDeclaredField("mHintId");
mHintId.setAccessible(true);
mHintId.setInt(si, R.string.your_custom_hint);
} catch (Exception e) {
}
MenuItem mi = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView)mi.getActionView();
searchView.setSearchableInfo( si );
}
Thanks Mister Murakami for the idea, i have implemented the same concept to perform toggle search and as per my view its not a hack but its beauty of OOPs. Below program having a toggle icon in the action bar to switch between search hint.
RestaurantListingActivity.java
public class RestaurantListingActivity extends BaseMainActivity implements
TabListener {
private boolean isRestaurantSearch = true;
private SearchManager searchManager;
private SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar aBar = getActionBar();
aBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
aBar.addTab(aBar.newTab().setText("Place Order").setTabListener(this));
aBar.addTab(aBar.newTab().setText("My Account").setTabListener(this));
aBar.addTab(aBar.newTab().setText("Favorite").setTabListener(this));
aBar.addTab(aBar.newTab().setText("Vendor Portal").setTabListener(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.restaturant_listing_menu, menu);
searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.rlm_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(new ComponentName(this,
RestaurantListingActivity.class)));
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.rlm_toggle:
isRestaurantSearch = !isRestaurantSearch;
if (isRestaurantSearch)
searchView.setSearchableInfo(searchManager
.getSearchableInfo(new ComponentName(this,
RestaurantListingActivity.class)));
else
searchView.setSearchableInfo(searchManager
.getSearchableInfo(new ComponentName(this,
RestaurantFoodSwitcherActivity.class)));
break;
case R.id.rlm_change_loc:
break;
case R.id.rlm_filter_search:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void setScreenData(Object screenData, int event, long time) {
// TODO Auto-generated method stub
}
#Override
public Activity getMyActivityReference() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
restaurant_listing_menu
<item
android:id="#+id/rlm_toggle"
android:showAsAction="always"
android:title="Toggle Search"
android:icon="#drawable/ic_action_refresh"
>
</item>
<item
android:id="#+id/rlm_search"
android:showAsAction="always|collapseActionView"
android:title="Search"
android:icon="#drawable/ic_action_search"
android:actionViewClass="android.widget.SearchView"
>
</item>
<item
android:id="#+id/rlm_filter_search"
android:showAsAction="ifRoom"
android:title="Filter Search"
android:icon="#drawable/ic_action_settings"
>
</item>
<item
android:id="#+id/rlm_change_loc"
android:showAsAction="ifRoom"
android:title="Change Location"
android:icon="#drawable/ic_action_location_off"
>
</item>
searchablerestra.xml inside res>xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint_restra"
android:label="#string/app_name">
</searchable>
RestaurantFoodSwitcherActivity.java
public class RestaurantFoodSwitcherActivity extends RestaurantListingActivity {
}
searchablefood.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint_food"
android:label="#string/app_name">
</searchable>
manifest.xml
<activity android:name="com.example.app.ui.activity.RestaurantListingActivity" >
<!-- This intent-filter identifies this activity as "searchable" -->
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- This metadata entry provides further configuration details for searches -->
<!-- that are handled by this activity. -->
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchablerestra"
/>
</activity>
<activity android:name="com.example.app.ui.activity.RestaurantFoodSwitcherActivity">
<!-- This intent-filter identifies this activity as "searchable" -->
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- This metadata entry provides further configuration details for searches -->
<!-- that are handled by this activity. -->
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchablefood"
/>
</activity>

Categories

Resources