Reputation: 23
I am trying to initialize custom search tool (3d library ) on menu but I got error.
Here is my code
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.base_nav_drawer,menu)
searchItem= menu?.findItem(R.id.srchbar_menu)!!
global_search= searchItem.actionView as MaterialSearchBar
lastsuggestions=ArrayList<String>()
loadSuggest()
global_search.lastSuggestions=lastsuggestions
return true
}
Logcat message
kotlin.TypeCastException: null cannot be cast to non-null type com.mancj.materialsearchbar.MaterialSearchBar
at com.example.sg772.foodorder.BaseNavDrawerActivity.onCreateOptionsMenu(BaseNavDrawerActivity.kt:136)
I tried this
global_search= searchItem.actionView as? MaterialSearchBar
But it doesnt help
line 136 corresponds to global_search= searchItem.actionView as MaterialSearchBar
xml of menu
<?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/srchbar_menu"
android:title="search"
android:icon="@drawable/ic_search_black_24dp"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="com.mancj.materialsearchbar.MaterialSearchBar"/>
</menu>
Upvotes: 1
Views: 2015
Reputation: 14193
This line make your app crash
global_search = searchItem.actionView as MaterialSearchBar
Because searchItem.actionView
always returns null
and global_search
type is MaterialSearchBar
(non-null type). You assign null to a non-null type, that why your app crash.
You can change your code to
var global_search: MaterialSearchBar? = null
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.base_nav_drawer,menu)
searchItem= menu?.findItem(R.id.srchbar_menu)!!
global_search = searchItem.actionView as MaterialSearchBar?
lastsuggestions=ArrayList<String>()
loadSuggest()
global_search.lastSuggestions=lastsuggestions
return true
}
But the search view does not show on your app, it seems 3rd party does not support to integrate into a menu item by using app:actionViewClass
.
Here is a workaround solution that you can try.
https://github.com/mancj/MaterialSearchBar/issues/107
Upvotes: 1
Reputation: 2719
if this doesn't help
global_search= searchItem.actionView as? MaterialSearchBar
global_search
is probably declared as Non-Nullable
Make sure it is
var global_search: MaterialSearchBar? = null
Upvotes: 0
Reputation: 5259
Most likely your actionView member is null and you might want to use:
global_search= searchItem.actionView as MaterialSearchBar?
or in definition something like this:
var global_search:MaterialSearchBar?= searchItem.actionView
PS. It would be beneficial if you show how global_search was defined
Upvotes: 0