简体   繁体   中英

Getting Null Pointer Exception when calling an Activity from onMenuItemClick() method

public class MainActivity extends FragmentActivity implements ActionBar.TabListener, OnMenuItemClickListener, OnClickListener {

    private PopupMenu popupMenu;
    private final static int ONE = 1;
    private final static int TWO = 2;
    private final static int THREE = 3;
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);


        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_settings:

             /*View menuItemView = findViewById(R.id.action_settings);
             PopupMenu popupMenu = new PopupMenu(this, menuItemView); 
                popupMenu.inflate(R.menu.counters_overflow);
                popupMenu.show();*/

            popupMenu = new PopupMenu(this, findViewById(R.id.action_settings));
            popupMenu.getMenu().add(Menu.NONE, ONE, Menu.NONE, "Set Password");
            popupMenu.getMenu().add(Menu.NONE, TWO, Menu.NONE, "About");
            //popupMenu.getMenu().add(Menu.NONE, THREE, Menu.NONE, "Item 3");
            popupMenu.setOnMenuItemClickListener(this);
            findViewById(R.id.action_settings).setOnClickListener(this);
        }
        return (super.onOptionsItemSelected(item));
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }    

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
                case 3:
                    return getString(R.string.title_section4).toUpperCase(l);

            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";

        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
            TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case ONE:
            getActionBar().hide();
            //setContentView(R.layout.setpassword);
            Intent intent = new Intent(this, SetPassword.class);
            startActivity(intent);
            break;
        case TWO:
            break;
        }
        return false;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        popupMenu.show();
    }
}

LOG CAT

06-10 09:38:36.836: E/AndroidRuntime(790): FATAL EXCEPTION: main 06-10 09:38:36.836: E/AndroidRuntime(790): java.lang.RuntimeException: Unable to start activity ComponentInfo{split.pack.doasplit/split.pack.doasplit.SetPassword}: java.lang.NullPointerException 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.ActivityThread.access$600(ActivityThread.java:141) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.os.Handler.dispatchMessage(Handler.java:99) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.os.Looper.loop(Looper.java:137) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.ActivityThread.main(ActivityThread.java:5041) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at java.lang.reflect.Method.invokeNative(Native Method) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at java.lang.reflect.Method.invoke(Method.java:511) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at dalvik.system.NativeStart.main(Native Method) 06-10 09:38:36.836: E/AndroidRuntime(790):
Caused by: java.lang.NullPointerException 06-10 09:38:36.836: E/AndroidRuntime(790):
    at split.pack.doasplit.SetPassword.onCreate(SetPassword.java:32) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.Activity.performCreate(Activity.java:5104) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 06-10 09:38:36.836: E/AndroidRuntime(790):
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 06-10 09:38:36.836: E/AndroidRuntime(790):
    ... 11 more

You are getting a NullPointerException when you're creating SetPassword activity, specifically, on line 32 of SetPassword.java (check the bottom of the logcat).

In your onMenuItemClick method, you're creating an intent and starting activity SetPassword , which throws the exception.

Edit:

The Exception is in your SetPassword class not in this one post the code of setpassword or check the line 32 in the SetPassword class.

Check the theme you have taken in android manifest file for your application, ie does your current theme is having action bar because you wrote getActionBar().hide(); in the code and it might be throwing exception if the theme you have choosen with no action bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM