Android 代码中的 NullPointerException [英] NullPointerException in Android code

查看:35
本文介绍了Android 代码中的 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误是:

java.lang.NullPointerException.onCreateOptionsMenu(AddMyMarketsActivity.java:44)

我的代码是:

41 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
42          SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
43          SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();       
44          searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            Log.i("searchView", "set searchable configuration for searchView ");

我的代码可能有什么问题?

What could be the problem with my code?

推荐答案

如果您使用 androids support libary 来显示您的操作栏,请确保您在 SearchView 声明中使用正确的 actionViewClass.

If you're using androids support libary to display your action bar, be sure you use the right actionViewClass in your SearchView declaration.

应该是 app:actionViewClass="android.support.v7.widget.SearchView".

之后,您可以将其用作尝试获取 ActionView 的代码的替代品:

After that you can use as replacement for your code trying to get the ActionView:

MenuItem searchItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

在调用之前一定要调用 getMenuInfalter().inflate(...) .

Be sure to call getMenuInfalter().inflate(...) before calling this.

更多信息:http://developer.android.com/guide/topics/ui/actionbar.html#ActionView

这篇关于Android 代码中的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆