java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.test.apptest.Home.HomePageActivity.onCreateOptionsMenu(HomePageActivity.java:366)
第366行为:
ImageView searchIcon = (ImageView)searchView.findViewById(R.id.search_mag_icon);
显然,我正在尝试使用具有空值的对象引用。我试图了解问题出在哪里,在这里我分享了部分代码片段:
HomePageActivity.java
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
Drawable drawable = menu.findItem(R.id.action_search).getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.parseColor(sharedObjects.getPrimaryColor()), PorterDuff.Mode.SRC_ATOP);
}
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
ImageView searchIcon = (ImageView)searchView.findViewById(R.id.search_mag_icon); // <-- Here is the error
searchIcon.setColorFilter(Color.parseColor(sharedObjects.getPrimaryColor()));
ImageView searchClose = searchView.findViewById(R.id.search_close_btn);
searchClose.setColorFilter(Color.parseColor(sharedObjects.getPrimaryColor()));
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
EditText searchEditText = (EditText) searchView.findViewById(R.id.search_src_text);
searchEditText.setTextColor(Color.BLACK);
searchEditText.setHintTextColor(Color.parseColor(sharedObjects.getFooterColor()));
searchEditText.setTextColor(Color.parseColor(sharedObjects.getPrimaryColor()));
searchEditText.setDrawingCacheBackgroundColor(Color.parseColor(sharedObjects.getPrimaryColor()));
searchEditText.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor(sharedObjects.getPrimaryColor())));
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.e("Submit", query);
(menu.findItem(R.id.action_search)).collapseActionView();
Intent intent = new Intent(HomePageActivity.this, SearchActivity.class);
intent.putExtra(AppConstants.KEYWORD, query);
startActivity(intent);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
Log.e("TextChange", newText);
return false;
}
});
return true;
}
UPDATE
这是完整代码:
activity_homepage.xml:https://www.codepile.net/pile/X5yWyp18
HomePageactivity.java:https://www.codepile.net/pile/oJyYQWJK
任何帮助,我们都会在整个下午进行调查,我们将不胜感激
从堆栈跟踪中可以明显看出,您要在其上调用方法searchView
的对象findViewById(R.id.search_mag_icon)
为空。因此,为了解决此错误:
首先检查,如果myActionMenuItem.getActionView()
是否返回null。