如何解决活动和片段通信错误?

时间:2016-02-29 18:53:00

标签: android android-fragments searchview

在线教程显示这适用于其他人。我的代码在这里显示错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void pl.michalz.hideonscrollexample.fragment.PartThreeFragment.volleyJson()' on a null object reference
            at pl.michalz.hideonscrollexample.activity.partthree.PartThreeActivity$1.onQueryTextSubmit(PartThreeActivity.java:59)
            at android.support.v7.widget.SearchView.onSubmitQuery(SearchView.java:1156)
            at android.support.v7.widget.SearchView.access$900(SearchView.java:101)
            at android.support.v7.widget.SearchView$9.onEditorAction(SearchView.java:1134)
            at android.widget.TextView.onEditorAction(TextView.java:4770)
            at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:139)
            at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:304)
            at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

SearchView正在侦听搜索查询mainActivity类,我想在使用ViewPager在mainActivity中创建的片段中使用recyclelerView中的搜索查询:

public class PartThreeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppThemeBlue);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_part_three);
        Log.w("myApp", "onCreate -started- ");
        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);

        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 query = " + query);

                        PartThreeFragment fragment = (PartThreeFragment) getSupportFragmentManager().findFragmentById(R.id.recyclerView);
                        fragment.volleyJson();
                        return false;
                    }

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


    private void initToolbar() {
        Log.w("myApp", "initToolbar -started- ");
        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);

        }
    }

}

解决方案编辑1:

public class PartThreeActivity extends AppCompatActivity {
    PagerAdapter pagerAdapter;
...

    public boolean onQueryTextSubmit(String query) {
        Log.w("myApp", "onQueryTextSubmit query = " + query);
        PartThreeFragment fragment = (PartThreeFragment) pagerAdapter.fragmentList.get(0);
        fragment.volleyJson();
        return false;
    }

1 个答案:

答案 0 :(得分:1)

这一行:

PartThreeFragment fragment = (PartThreeFragment) getSupportFragmentManager().findFragmentById(R.id.recyclerView);

返回null。仔细检查您是否正在寻找正确的ID。