【问题标题】:Why setOnQueryTextListener() gets "on a null object reference" error?为什么 setOnQueryTextListener() 会出现“在空对象引用上”错误?
【发布时间】:2016-06-10 09:59:26
【问题描述】:

我正在尝试将搜索图标添加到工具栏,按下会打开搜索栏。

但是我尝试的每种方法都不起作用,并且没有出现任何图标。 现在我收到此错误,但找不到解决方案:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference
    at pl.michalz.hideonscrollexample.activity.partthree.PartThreeActivity.onCreateOptionsMenu(PartThreeActivity.java:62)

这是我的主要活动

public class PartThreeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppThemeBlue);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_part_three);

        initToolbar();
        initViewPagerAndTabs();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem seachItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)
                MenuItemCompat.getActionView(seachItem);

        searchView.setOnQueryTextListener(
            new SearchView.OnQueryTextListener(){

            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d("myApp", "onQueryTextSubmit ");
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d("myApp", "onQueryTextChange ");
                return false;
            }
        });

        return true;
    }

    private void initToolbar() {
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        setTitle(getString(R.string.app_name));
        mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
    }

    private void initViewPagerAndTabs() {
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
        pagerAdapter.addFragment(PartThreeFragment.createInstance(), getString(R.string.tab_1));
        pagerAdapter.addFragment(BlankFragment.createInstance("F word"), getString(R.string.tab_2));
        viewPager.setAdapter(pagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    static class PagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> fragmentList = new ArrayList<>();
        private final List<String> fragmentTitleList = new ArrayList<>();

        public PagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        public void addFragment(Fragment fragment, String title) {
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return fragmentTitleList.get(position);
        }
    }


    //kai paskaudzia toolbaro iconas
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                // User chose the "Settings" item, show the app settings UI...
                return true;

            case R.id.action_search:
                // User chose the "Favorite" action, mark the current item
                // as a favorite...
                return true;

            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

}

主 Activity.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways|snap" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="6dp"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextColor="@android:color/white" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</android.support.design.widget.CoordinatorLayout>

还有searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/hint"
    android:label="@string/app_name" />

还有res/menu/menu_main.xml,自己添加了ic_search到drawable

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/tools">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search"
        android:title="@string/action_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom|collapseActionView" />


    <!-- Settings, should always be in the overflow -->
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        app:showAsAction="never" />

</menu>

有人可以帮忙吗?

【问题讨论】:

    标签: android xml searchview


    【解决方案1】:

    我遇到了同样的问题。解决方案很简单。

    在执行 alt+enter 时始终检查导入

    我执行了 alt+enter 并导入了 android.widget.SearchView,而我的实现预期 android.support.v7.widget.SearchView

    【讨论】:

      【解决方案2】:

      我通过将 menu_main.xml 中的命名空间从 app 更改为我自己的 myapp 来修复错误,并通过按“Alt+Enter”自动修复。

      res/menu/menu_main.xml

      <menu xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/tools"
          //----------- it created automaticly --------------
          xmlns:myapp="http://schemas.android.com/apk/res-auto">
      
          <item
              android:id="@+id/action_search"
              android:icon="@drawable/ic_search"
              android:title="@string/action_search"
              //-------------- H E R E --------------------
              myapp:showAsAction="always|collapseActionView"
              myapp:actionViewClass="android.support.v7.widget.SearchView" />
      
          <!-- Settings, should always be in the overflow -->
          <item
              android:id="@+id/action_settings"
              android:title="@string/action_settings"
              app:showAsAction="never" />
      
      </menu>
      

      主要活动

      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.menu_main, menu);
      
          Log.w("myApp", "onCreateOptionsMenu -started- ");
      
          SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
          MenuItem menuItem = menu.findItem(R.id.action_search);
          SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
      
          searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()));
          searchView.setQueryHint(getResources().getString(R.string.hint));
      
          searchView.setOnQueryTextListener(
              new SearchView.OnQueryTextListener(){
                  @Override
                  public boolean onQueryTextSubmit(String query) {
                  Log.w("myApp", "onQueryTextSubmit ");
                      return false;
                  }
      
                  @Override
                  public boolean onQueryTextChange(String newText) {
                      Log.w("myApp", "onQueryTextChange ");
                      return false;
                  }
          });
      
          return true;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多