调用SearchView.setOnQueryTextListener触发空指针异常的原因排查
空指针根因定位
- 核心错误:
onCreateView内的代码执行顺序完全颠倒。你将所有控件初始化、设置SearchView监听、配置RecyclerView的逻辑,全部写在了布局inflate语句之前。直到函数最后一行才执行return inflater.inflate(R.layout.fragment_search, container, false),这行执行前Fragment的视图树根本没有被创建,你持有的searchBar等控件引用完全没有绑定到实际布局上,自然是空对象,调用其方法就会触发空指针。 - 次生错误:控件引用混乱。你前面为
homeRecycler配置了Adapter,但在搜索过滤回调里却调用searchRecycler.adapter触发列表更新,两个不同的控件对象,就算布局加载完成,这里依然会因为searchRecycler未初始化触发空指针。
其他会触发运行崩溃的代码问题
- 主线程阻塞风险:你在主线程用
runBlocking执行Room数据库查询,既会阻塞主线程造成ANR,也会触发Room默认的“不允许主线程访问数据库”的运行异常。 - 列表更新逻辑错误:你把
notifyDataSetChanged()写在了for循环内部,每遍历一个列表项就触发一次全量列表重绘,会造成严重的性能问题,应该等整个过滤流程走完再一次性触发更新。 - 非空断言风险:代码里大量使用
!!做非空判断,比如mContext!!、notesList!!,只要任何一个引用为空就会直接崩溃,没有兜底逻辑。
修正后的代码实现
override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // 第一步:先加载根布局 val root = inflater.inflate(R.layout.fragment_search, container, false) // 第二步:从根布局绑定所有控件,此时控件引用才会正确赋值 val searchBar: SearchView = root.findViewById(R.id.searchBar) val homeRecycler: RecyclerView = root.findViewById(R.id.homeRecycler) // 初始化数据容器 val fullNoteList = arrayListOf<Note>() val showList = arrayListOf<Note>() // 配置RecyclerView val layoutManager = GridLayoutManager(requireContext(), 2, LinearLayoutManager.VERTICAL, false) val noteAdapter = NoteAdapter(requireContext(), showList) homeRecycler.layoutManager = layoutManager homeRecycler.adapter = noteAdapter // 协程切IO线程查数据库,避免阻塞主线程 viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) { val db = NotesDB.getAppDB(requireContext()) ?: return@launch val allNotes = db.noteDao().getAll() fullNoteList.addAll(allNotes) showList.addAll(allNotes) // 切回主线程配置搜索逻辑、更新列表 withContext(Dispatchers.Main) { noteAdapter.notifyDataSetChanged() searchBar.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?) = true override fun onQueryTextChange(newText: String?): Boolean { showList.clear() val searchKey = newText?.lowercase(Locale.getDefault())?.trim().orEmpty() if (searchKey.isNotEmpty()) { // 从全量数据中过滤匹配项 val matchedNotes = fullNoteList.filter { it.name.lowercase(Locale.getDefault()).trim().contains(searchKey) } showList.addAll(matchedNotes) } else { // 搜索词为空时恢复全量列表 showList.addAll(fullNoteList) } // 过滤完成后一次性通知列表更新 noteAdapter.notifyDataSetChanged() return true } }) } } return root }
内容的提问来源于stack exchange,提问作者user15876680
相关产品推荐
相关产品推荐

