NullPointerException on SearchView using ActionBarSherlock - android

I am using ActionBarSherlock and Support Library v4. This is in a `SherlockFragmentActivity'.
I am getting a Nullpointer on line 269, referenced below. I have verified SearchView is null, not SearchManager. Though, menu is also null as well, I am not sure if that is normal? Important: It is ONLY null in my Android 4.0 and 4.1 tests. In 2.3, it works great!
Here is my SearchView Code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu, menu);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView(); // line 269
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setSubmitButtonEnabled(true);
return true;
}
I have this as my menu item now.
<item
android:id="#+id/menu_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#android:drawable/ic_menu_search"
android:showAsAction="always"
android:title="search"/>
LogCat
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.---.---.master.MainFragmentActivity
.setupSearchView(MainFragmentActivity.java:269)
at com.---.---.master.MainFragmentActivity.onCreateOptionsMenu(
MainFragmentActivity.java:258)
at android.support.v4.app.Watson.onCreatePanelMenu(Watson.java:45)
at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(
ActionBarSherlock.java:559)
at com.actionbarsherlock.internal.ActionBarSherlockCompat.preparePanel(
ActionBarSherlockCompat.java:479)
at com.actionbarsherlock.internal.ActionBarSherlockCompat
.dispatchInvalidateOptionsMenu(ActionBarSherlockCompat.java:272)
at com.actionbarsherlock.internal.ActionBarSherlockCompat$1.run(
ActionBarSherlockCompat.java:984)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(
ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
imports:
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import android.app.SearchManager;
Again, I get Null Pointer in ONLY the 4.0 emulator and 4.1 device. App runs great in 2.3. At one time, pre-ActionBarSherlock, using the SAME code, except importing SearchView through the normal way (not Sherlock) it worked great in 4.0. I am trying to make my app backwards compatible and is broke the newer Android versions, but works great in the older.
EDIT: It was actually Null in 2.3 and Cast Issue in 4.0+ when the menu item had android:actionViewClass="android.app.SearchView"
Then I changed it to android:actionViewClass="com.actionbarsherlock.widget.SearchView"
and now FIXED in 2.3 and Null in 4.0+
UPDATE: I appeared to fix it with a hack:
I added a menu-v11 folder added a duplicate file of menu.xml with one item change only: android:actionViewClass="android.app.SearchView", otherwise it is identical to the other menu.xml file.
In Java, I did this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setSubmitButtonEnabled(true);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setupNewSearchView(searchItem, searchManager);
}
return true;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupNewSearchView(MenuItem searchItem,
SearchManager searchManager) {
android.widget.SearchView searchView =
(android.widget.SearchView) searchItem.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setSubmitButtonEnabled(true);
}
Well, it works, but I'm not putting it as an answer yet because it seems like hack way of doing it. Open to better ideas?

There is a problem with missing attrs for v14 (and v11?) in ActionBarSherlock (or ActionBarSherlock + HoloEverywhere + Theme.Sherlock.Light.DarkActionBar ?).
Simple solution and details in the issue thread…

You are trying to use two completely different classes, both named SearchView but in different packages. You cannot simply cast an object from one class into another class. com.actionbarsherlock.widget.Searchview is different than android.widget.SearchView. Therefore, searchView is null on line 269.
It would be relevant for us to see the imports from the top of your Java file.
Probably, the view referenced by R.id.menu_search is an android.widget.SearchView and your code expects it to be a com.actionbarsherlock.widget.Searchview.

Add a theme attribute to your manifest file under the tags of each of the activities that you plan to use an ActionBar. You can create your own custom theme or use one of the default offered by ActionBarSherlock.
<activity
android:name="com.example.MyActivityWithActionBar"
...
android:theme="#style/Theme.Sherlock.Light">
</activity>
More information on:
http://actionbarsherlock.com/theming.html
http://developer.android.com/guide/topics/ui/themes.html#ApplyATheme

Related

How do I get my ActionBar Items to show as icons, and not in the overflow menu?

First off, I'm running the latest Lollipop - Minimum and targeted SDK are both 22
minSdkVersion 22
targetSdkVersion 22
in the gradle build. I've changed/re changed these to 22, as well as rebuilt/invalidated caches/cleaned. I'm extending Activity in my main:
public class login_activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.login_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
}
And here are my menu items:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/login_help"
android:icon="#android:drawable/ic_menu_help"
android:title="#string/login_help_text"
app:showAsAction="ifRoom"/>
</menu>
When I run my code, it keeps showing the items in the ActionBar overflow menu. How do I fix this? Thanks!
Try replacing "ifroom" with "always" for showAsAction like below
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/login_help"
android:icon="#android:drawable/ic_menu_help"
android:title="#string/login_help_text"
app:showAsAction="always"/>
</menu>
I actually spent nearly five hours trying to figure this out, but I actually figured it out just now going through my gradle files. Here's how you fix it:
Go to your Gradle Scripts folder
Open the build.gradle file with the SDK options in it
Remove the line under dependencies (Mine's this one, not sure how they vary):
compile 'com.android.support:appcompat-v7:22.2.0' (REMOVE THIS)
Go back to your menu file and REMOVE the namespace definition for the namespace you put before showAsAction
xmlns:app="http://schemas.android.com/apk/res-auto" (REMOVE THIS)
Go change the showAsAction line from something:showAsAction to android:showAsAction
Rebuild & compile. It should work! I wish changing the SDK cleaned up after itself, but hey, what can you do.

What are the common issues when migrating from ActionBarSherlock to ActionBarCompat?

I would like to remove ActionBarSherlock from my application and replace it with the standard ActionBarCompat.
How do I implement ActionBarCompat?
How do I migrate the Activites?
Which imports replace the ActionBarSherlock imports?
What are typical problems?
I did some migrating and wrote down all the issues I encountered. None were serious but took time to research. I was able to migrate a quite big application in a couple hours after knowing all this. May this help to speed up migration process.
How do I convert from ActionBarSherlock to ActionBarCompat?
Note: Since the Support Library's v22.1.0, the class ActionBarActivity is deprecated. You should use AppCompatActivity instead. Read here for more information: What's the enhancement of AppCompatActivity over ActionBarActivity?
== Switch the libraries ==
Go to app properties and remove ActionBarSherlock and add ActionBarCompat instead. This requires the v7 appcompat library to be present, see http://developer.android.com/tools/support-library/setup.html for details. Follow the instructions precisely, ActionBarCompat needs to be a library project.
Parallel does not work (easily) as a lot of attributes are in both libraries.
Do not be discouraged by hundreds of errors after replacing the libraries. The vast majority goes away automatically.
== Fix XML errors ==
First thing is to fix all XML errors to allow compiling and find other errors.
Replace the sherlock theme with ActionBarCompat Theme, e.g.
<style name="AppBaseTheme" parent="#style/Theme.AppCompat.Light.DarkActionBar">
Remove double attr, e.g. <attr name="buttonBarStyle" format="reference" />.
For now remove all your individual action bar styles. See further down how to handle these.
== Fix build errors ==
Pick the easiest activities first. ActionBarCompat does not distinguish Activity and FragmentActivity, both are now ActionBarActivity.
Remove the ActionBarSherlock imports and extend to ActionBarActivity (import android.support.v7.app.ActionBarActivity;)
After saving, this should dramatically reduce errors in the activity.
Fix the errors around the menues first and disregard fragment errors for now, they should be going away later.
== Replacements ==
Imports:
import com.actionbarsherlock.app.SherlockActivity; -> import android.support.v7.app.ActionBarActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity; -> import android.support.v7.app.ActionBarActivity;
import com.actionbarsherlock.app.SherlockFragment; -> import android.support.v4.app.Fragment;
import com.actionbarsherlock.app.SherlockListFragment; -> import android.support.v4.app.ListFragment;
import com.actionbarsherlock.app.SherlockListActivity; -> import android.support.v7.app.ActionBarActivity; (see ListActivity / SherlockListActivity)
import com.actionbarsherlock.view.Menu; -> import android.view.Menu;
import com.actionbarsherlock.view.MenuItem; -> import android.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater; -> import android.view.MenuInflater;
import com.actionbarsherlock.view.Window; -> import android.view.Window;
import com.actionbarsherlock.widget.SearchView; -> import android.support.v7.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener -> import android.support.v7.widget.SearchView.OnQueryTextListener;
Code Replacements:
SherlockActivity -> ActionBarActivity
SherlockFragmentActivity -> ActionBarActivity
SherlockListActivity -> ListActivity (see ListActivity / SherlockListActivity)
SherlockListFragment -> ListFragment;
getSupportMenuInflater -> getMenuInflater
getSherlockActivity() -> getActivity()
com.actionbarsherlock.widget.SearchView.OnQueryTextListener() -> OnQueryTextListener (see SearchView)
m.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); -> MenuItemCompat.setShowAsAction(m, MenuItem.SHOW_AS_ACTION_ALWAYS);
Typical Code changes for ActionBarCompat
getActionBar() -> getSupportActionBar()
invalidateOptionsMenu() -> supportInvalidateOptionsMenu()
== Fragment ==
The fragment does not cater for ActionBarCompat functionality. This is a problem when trying to call getSupportActionBar.
This can be solved by using the onAttach method:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((ActionBarActivity)activity).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
Usually this is better controlled in the FragmentActivity.
== SearchView ==
This turned out to be a bit of a hassle.
Replace something like this:
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
with
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
You also have to adjust your menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#android:drawable/ic_menu_search"
android:orderInCategory="80"
android:showAsAction="always|collapseActionView"
android:title="#string/action_search"/>
</menu>
with
<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="#android:drawable/ic_menu_search"
android:orderInCategory="80"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView"/>
</menu>
app: needs to be defined to have compatibility with android versions before 11.
SearchView needs to be support class v7.
== ListActivity / SherlockListActivity ==
The ListActivity is not supported ActionBarCompat, therefore the crucial functions of the ListActivity need to be implemented manual, which is rather simple:
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
== Styles ==
A styled action bar can be achieved, see original google posting:
http://android-developers.blogspot.de/2013/08/actionbarcompat-and-io-2013-app-source.html
A styled searchView box is more difficult:
This works:
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchView.SearchAutoComplete theTextArea = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
theTextArea.setTextColor(getResources().getColor(R.color.yourColor));
See these posts:
Changing the cursor color in SearchView without ActionBarSherlock
Change appcompat's SearchView text and hint color
== Example ==
Google Navigation Drawer with Action Bar Sherlock includes all original code (now aiming to support library) and formatting. Only some attributes had to be replaced with similar ones as they are only available from v11 onwards.
Download at: https://github.com/GunnarBs/NavigationDrawerWithActionBarCompat
== See also ==
http://android-developers.blogspot.de/2013/08/actionbarcompat-and-io-2013-app-source.html
http://developer.android.com/reference/android/support/v7/app/ActionBar.html
http://www.grokkingandroid.com/migrating-actionbarsherlock-actionbarcompat/
It is worth mentioning that there is no support version of the PreferenceActivity, so if you are using SherlockPreferenceActivity, you need to refactor to a support PreferenceFragment.
More info: How to add Action Bar from support library into PreferenceActivity?

Changing Searchable Icon in Actionbar

I'm implementing searchable for my application and I come to this problem. How can i change the default magnifying glass for my Searchable? The default looks big and fugly and I prefer to use the same drawable i used for my menu icon.
Searching "icon" in Searchable Configuration - Android Developer website doesn't lead to any useful information. I also tried by adding android:icon(It was an option in the Structure tab) to my searchable definition but it's not working.
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:icon="#drawable/ic_custom_test"
android:includeInGlobalSearch="true"
android:label="#string/search_label"
android:searchSettingsDescription="#string/settings_description"
android:searchSuggestAuthority="com.test.provider.SuggestionProvider"
android:searchSuggestIntentAction="android.intent.action.VIEW"
android:searchSuggestIntentData="content://com.test.provider.SuggestionProvider/info"
android:searchSuggestSelection=" ?"
android:searchSuggestThreshold="1" >
</searchable>
Thanks in advance for any helps!
Implement your own searchview, delete the search item from main.xml/activity_main(your layout filename) in menu folder, then create a new item and your own search icon,.,
use iconfinder.com for different icons.
in your activity, in options method, create a switch case and add the functionality when you click on this item.,.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
SearchManager localSearchManager1 = (SearchManager)getSystemService("search");
SearchView localSearchView1 = (SearchView)menu.findItem(R.id.search).getActionView();
localSearchView1.setSearchableInfo(localSearchManager1.getSearchableInfo(getComponentName()));
localSearchView1.setIconifiedByDefault(true);
if (Build.VERSION.SDK_INT >= 11)
{
SearchManager localSearchManager2 = (SearchManager)getSystemService("search");
SearchView localSearchView2 = (SearchView)menu.findItem(R.id.search).getActionView();
localSearchView2.setSearchableInfo(localSearchManager2.getSearchableInfo(getComponentName()));
localSearchView2.setIconifiedByDefault(true) ;
}

Getting a SearchView with MenuItemCompat (Android)

I am trying to implement the SearchView ActionBar item as android developers says but I am having some trouble.
(http://developer.android.com/guide/topics/ui/actionbar.html).
There are two mistakes that although I have looked for a lot, I have not been able to find the solution.
1) I have a problem with the class MenuItemCompat. It says:
The method getActionView(MenuItem) is undefined for the type MenuItemCompat
I can only use for this class the following methods:
setShowAsAction(item, actionEnum)
setActionView(item, view)
Here it is the code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.restloader, menu);
MenuItem searchItem = menu.findItem(R.id.search_menu);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// Configure the search info and add any event listeners
return super.onCreateOptionsMenu(menu);
}
2) There is a problem with this:
xmlns:myapp="http://schemas.android.com/apk/res-auto"
I don't understand why it is used but if google says it, it must be appropriate.
Error message:
Multiple annotations found at this line:
- error: No resource identifier found for attribute 'actionViewClass' in package
'com.example.pruebahttp3'
- error: No resource identifier found for attribute 'showAsAction' in package
'com.example.pruebahttp3'
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/search_menu"
android:orderInCategory="100"
android:title="#string/search"
android:icon="#drawable/ic_search_category_default"
myapp:showAsAction="ifRoom|collapseActionView"
myapp:actionViewClass="android.support.v7.widget.SearchView">
</item>
Thank you very much!
i have got the same problem, i solved it by using the follow code. Be care of your namespace.`
<!-- Search, should appear as action button -->
<item
android:id="#+id/action_search"
android:icon="#drawable/abc_ic_search"
share:showAsAction="ifRoom"
share:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/abc_searchview_description_search" />
`
For the 1st:Fixing the second one will fix this :)
For the 2nd:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res-auto" >
Change myapp to you application namespace com.xxx.xxx
Try to copy the lib files directly from yourFolder\sdk\extras\android\support\v7\appcompat\libs
I have a similar problem,but It occurs to me when i directly copy the JAR library file rather than following the android support library procedure. Try the opposite it might work for you.
Kinda weird if you ask me.

Android: Emulator won't open menu in app

I'm having a rather odd issue where the menu for an activity works totally fine on real device but not on the emulator.
I tried launching one of my older projects in the emulator that I remember the menus working in, and it also failed. I suppose some sort of update has caused this?
The code is simple...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem prefs = menu.add("Preferences");
prefs.setIcon(R.drawable.gear_01);
return true;
}
LogCat displays series of exceptions ultimately caused by:
E/AndroidRuntime(6714): Caused by: java.io.FileNotFoundException: res/drawable-hdpi/ic_menu_more.png
This actually happens not only in my applications but on the home screen to.
Any ideas for solutions?
Its hard to find error in your code.
So try this.Create one Folder in res named menu.Put this xml inside this folder
Make Sure you have icon in your drawable names ic_new_game,ic_help
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/new_game"
android:icon="#drawable/ic_new_game"
android:title="#string/new_game"
android:showAsAction="ifRoom"/>
<item android:id="#+id/help"
android:icon="#drawable/ic_help"
android:title="#string/help" />
</menu>
Override this method as you did
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}

Categories

Resources