0

I have read "What is a NullPointerException and how do I fix it?" and it does not answer my question.

Okay, so I've got a fragment as an inner class inside my activity. From the fragment, I am trying to invoke a method in the activity class to remove all tabs from a TabLayout, but for some reason, I am getting a NullPointerException when I try to assign the TabLayout code to its resource.

Here is the method to remove all the tabs:

public void removeAllTabs() {
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mTabLayout = findViewById(R.id.tabs);
    mViewPager = findViewById(R.id.container);

    int cnp = mSectionsPagerAdapter.getCount();
    while (cnp > 0) {
        mSectionsPagerAdapter.destroyItem(mViewPager, cnp - 1, mSectionsPagerAdapter.getItem(cnp - 1));
        mTabLayout.removeTabAt(cnp - 1);
        cnp--;
    }
}

Here is the code that calls it:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
        final Activity activity = getActivity();
        final MenuActivity menuAct = new MenuActivity();
        final MenuViewModel viewModel = ViewModelProviders.of(this, new MenuViewModelFactory(activity.getApplication(), MenuActivity.ResID)).get(MenuViewModel.class);
        viewModel.getAllMenuTitles().observe(this, new Observer<String[]>() {
            @Override
            public void onChanged(String[] strings) {
                final Spinner spinner = rootView.findViewById(R.id.spinner);
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, strings);
                adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
                spinner.setAdapter(adapter);

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                        menuAct.removeAllTabs();
                        SubMenuViewModel vm = ViewModelProviders.of(getParentFragment(), new SubMenuViewModelFactory(menuAct.getApplication(), i)).get(SubMenuViewModel.class);
                        vm.getSubMenus().observe(getActivity(), new Observer<String[]>() {
                            @Override
                            public void onChanged(@Nullable String[] strings) {
                                menuAct.populateTabs(strings);
                            }
                        });
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });
            }
        });

        return rootView;
    }

Here is the stack trace:

07-27 15:11:59.434 17744-17744/com.whatamidoingwithmylife.splitbill E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.whatamidoingwithmylife.splitbill, PID: 17744
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.whatamidoingwithmylife.splitbill/com.whatamidoingwithmylife.splitbill.MenuActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
        at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
        at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
        at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
        at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
        at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
        at com.whatamidoingwithmylife.splitbill.MenuActivity.<init>(MenuActivity.java:48)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Siku M.
  • 99
  • 1
  • 9
  • 1
    You've got at least one `findViewById()` call in a field initializer in `MenuActivity`. You need to move that call into `onCreate()`, after the `setContentView()` call. – Mike M. Jul 27 '18 at 13:31
  • Okay I've done that, now I'm crashing at `int cnp = mSectionsPagerAdapter.getCount();` – Siku M. Jul 27 '18 at 13:34
  • 1
    Well, that's a different issue. What's the new Exception message? – Mike M. Jul 27 '18 at 13:36
  • `java.lang.NullPointerException: Attempt to invoke virtual method 'int com.whatamidoingwithmylife.splitbill.MenuActivity$SectionsPagerAdapter.getCount()' on a null object reference` – Siku M. Jul 27 '18 at 13:37
  • 1
    Did you mean the `int cnp = mSectionsPagerAdapter.getCount();` line you posted in `removeAllTabs()`? 'cause that doesn't really make sense. Also, is it still crashing when `MenuActivity` starts, or when you do something else? – Mike M. Jul 27 '18 at 13:42
  • Yes, that is what I meant. There is only one `int cnp = mSectionsPagerAdapter.getCount();` and it's inside `removeAllTabs()`. It also crashes like a third of a second after `MenuActivity` starts. – Siku M. Jul 27 '18 at 13:43
  • I assume that `Spinner` is in the `Fragment`? How exactly are you initializing `menuAct` there? – Mike M. Jul 27 '18 at 13:48
  • I've edited the post with the `Fragment`'s entire `onCreateView()` – Siku M. Jul 27 '18 at 13:49
  • 1
    Yeah, that's what I figured, but it didn't quite jive with the described behavior. Anyway, `final MenuActivity menuAct = new MenuActivity();`. Never, ever do that. You cannot instantiate an `Activity` yourself, and have it work correctly. Besides, `getActivity()` is the hosting `Activity` already. – Mike M. Jul 27 '18 at 13:54
  • I did that because I want to access non-static methods in MenuActivity. What do you suggest I do instead? Because getActivity() gives an error. – Siku M. Jul 27 '18 at 13:57
  • `final MenuActivity menuAct = (MenuActivity) getActivity();`. It's usually preferable to implement an interface for that kind of `Fragment`-`Activity` communication, but if `MenuActivity` is the only place you're using that `Fragment`, that's fine. – Mike M. Jul 27 '18 at 14:00
  • Don't create a new pager adapter every time the configuration changes... You never associate the new pager adapter with your view pager (e.g. by calling `mViewPager.setAdapter(mSectionsPagerAdapter);`) – Tyler V Jul 27 '18 at 14:14
  • 1
    @MikeM. Hey it works now from doing the `(MenuActivity) getActivity();` now. Thanks! Now I just need to fix the crashing getApplication(). – Siku M. Jul 27 '18 at 14:37
  • @TylerV It was associated in `onCreate()`. But in any case, I've since fixed it. Thanks – Siku M. Jul 27 '18 at 14:38

0 Answers0