首页 > 解决方案 > Android Studio - setQuery 在第一次搜索时不起作用

问题描述

我正在开发一个基于中文字典的 android 应用程序。我正在使用 handleIntent 进行来自不同活动的原始搜索。计划是打印这些结果并将查询保留在搜索栏中。

我的问题是查询在更改为结果活动时消失了,但是在第一个搜索之后的所有其他搜索在搜索栏中都有查询(据此我假设 onNewIntent 正在工作,但不是 HandleIntent)。它正在执行搜索,我只想让查询留在搜索栏中。

我已经使用调试器通过打印变量来确保通过函数执行查询,并且它可以毫无问题地执行任务,但是在尝试使用 setQuery 之后,整个事情在模拟器上崩溃了。

logcat 是这样写的:

原因:java.lang.NullPointerException:尝试在 celadondragon.com.activities 的空对象引用上调用虚拟方法 'void android.support.v7.widget.SearchView.setQuery(java.lang.CharSequence, boolean)'

    //Handles the original search from a different activity
@Override
protected void handleIntent(Intent intent) {
    //boolean mybool = Intent.ACTION_SEARCH.equals(intent.getAction());
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        final String query = intent.getStringExtra(SearchManager.QUERY);
        searchDictionary(query);

        searchView.post(new Runnable() {

            @Override
            public void run() {
                // Important! Make sure searchView has been initialized
                // and referenced to the correct (current) SearchView.
                // Config changes (e.g. screen rotation) may make the
                // variable value null.
                searchView.setQuery(query, false);
            }
        });
    }
}

标签: javaandroidnullpointerexceptionandroid-emulatorlogcat

解决方案


推荐阅读