-3

I want to make a communication between my fragment and main activity so I need to get switch.isCheked but get:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new NotesFragment()).commit();
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        final   NotesFragment notesFragment = new NotesFragment();
        final   RemindersFragment remindersFragment = new RemindersFragment();
        final   SettingsFragment settingsFragment = new SettingsFragment();

        final Switch aSwitch =    settingsFragment.getView().findViewById(R.id.switch_pop_up);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                Fragment selectedFragment = null;

                switch (menuItem.getItemId()) {
                    case R.id.action_notes:
                        if(aSwitch.isChecked())
                        Toast.makeText(MainActivity.this, "Your Notes", Toast.LENGTH_SHORT).show();
                        selectedFragment = notesFragment;
                        break;
                    case R.id.action_reminders:
                        if(aSwitch.isChecked())
                        Toast.makeText(MainActivity.this, "Your Reminders", Toast.LENGTH_SHORT).show();
                        selectedFragment = remindersFragment;
                        break;
                    case R.id.action_settings:
                        if(aSwitch.isChecked())
                        Toast.makeText(MainActivity.this, "Settings", Toast.LENGTH_SHORT).show();
                        selectedFragment = settingsFragment;

                        break;
                }
                assert selectedFragment != null;
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();
                return true;
            }
        });
    }
}

SettingsFragment.java

public class SettingsFragment extends Fragment {

    Switch switch_pop_up;
    boolean stateSwitchPopUp;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_settings, null);

       switch_pop_up  = v.findViewById(R.id.switch_pop_up);


        return inflater.inflate(R.layout.fragment_settings,container,false);
    }
}

I think it is because of :

final Switch aSwitch = settingsFragment.getView().findViewById(R.id.switch_pop_up);

How can I fix this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
brkas
  • 9
  • 2

2 Answers2

0

On your fragment, in the onCreateView method, change this line:

View v = inflater.inflate(R.layout.fragment_settings, null);

into:

View v = inflater.inflate(R.layout.fragment_settings, container, false);

Edit 1: This happens because you're doing v.findViewById(), but you're not returning v on onCreateView().

Change your return line in the fragment to return v;

Edit 2:

Add a getter on the fragment to the switch_pop_up:

public Switch getSwitchPopUp() {
    return switch_pop_up;
}

On your activity, replace this line:

final Switch aSwitch = settingsFragment.getView().findViewById(R.id.switch_pop_up);

with:

final Switch aSwitch = settingsFragment.getSwitchPopUp();

And you'll have to inflate your SettingsFragment before this line.

Note: Whichever result you need, this is not a good aproach anyway, so you might want to look into other ways to do it.

John Sardinha
  • 3,566
  • 6
  • 25
  • 55
  • Cant make it null, only false and true, tried to false and all was like it was before :( – brkas Feb 18 '19 at 16:47
  • What happens when you try with `inflater.inflate(R.layout.fragment_settings, container, false);` ? – John Sardinha Feb 18 '19 at 16:57
  • See edit please – John Sardinha Feb 18 '19 at 16:58
  • :с Ok, I did it, but idk why also crashing with NullPointerException:Attempt to invoke virtual method 'android.view.View.findViewById(int)' on a null object reference – brkas Feb 18 '19 at 17:09
  • That happens because you're doing `v.findViewById()`, but you're not returning `v` on `onCreateView()`. Change your `return ...` line in the fragment to `return v;` – John Sardinha Feb 18 '19 at 17:12
  • I also did it before texted last comm – brkas Feb 18 '19 at 17:13
  • Are you trying with `View v = inflater.inflate(R.layout.fragment_settings, container, false);` and `return v` ? – John Sardinha Feb 18 '19 at 17:15
  • `public class SettingsFragment extends Fragment { Switch switch_pop_up; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_settings,container,false); switch_pop_up = v.findViewById(R.id.switch_pop_up); return v; } } ` It now looks like this, sry idk how to make good view of comment :с – brkas Feb 18 '19 at 17:17
  • Hmm this should work, weird. Try removing @NonNull from the LayoutInflator – John Sardinha Feb 18 '19 at 17:21
  • Can it be some troubles with `final Switch aSwitch = settingsFragment.getView().findViewById(R.id.switch_pop_up);` ? – brkas Feb 18 '19 at 17:31
  • Oh, I thought the error was in the fragment. Yeah you can't access the fragment like that in your activity. Let me edit my answer. – John Sardinha Feb 18 '19 at 17:35
  • Please see edit 2 – John Sardinha Feb 18 '19 at 17:38
  • Omg that isnt crashing nomore when I open app, but no there is crashing when I clicking to the Settings with NullPointerException:Attempt to invoke virtual method 'boolean android.widget.Switch.isChecked()' on a null object reference It is like in 48 line in my MainActivity By the way thank you so much – brkas Feb 18 '19 at 17:51
  • Also, I can see from your code, that your switch button is on your Settings screen, but you're checking if it's checked or not when your tap the Notes and Reminders items in the bottom menu - but you won't be able to access the switch button if you're not on the Settings fragment. – John Sardinha Feb 18 '19 at 17:54
  • Ok, thank you. I understood, but then how can I get the isChecked of this button, like when it is false there are not showing Toasts when I changing fragments – brkas Feb 18 '19 at 17:59
  • If you want to get the isChecked of the switchbutton while you're on another fragment, then a good option is to use [SharedPreferences](https://stackoverflow.com/a/23024962/5905035) – John Sardinha Feb 18 '19 at 18:08
  • so, I dont understand a bit, where do I need to make It with click listener - in the fragment or MainActivity? – brkas Feb 18 '19 at 18:29
0

The problems are:

  1. you are not attaching your SettingsFragment to activity to make it visible on screen (like you do with your NotesFragment)
  2. you're trying to access it's child views from your MainActivity's onCreate method.

Fragments get initialized after activity is being created and ready to host them. Therefore, settingsFragment.getView() is returning null. It's onCreateView lifecycle method has not being called yet.

You need to reconsider your approach and try to find other solution. I suggest you to read this threads in SO to get more ideas on how to solve your problem.

How to access Fragment's child views inside fragment's parent Activity?

Access Fragment View from Activity's onCreate

Android: how to notify Activity when Fragments views are ready?

Marat
  • 6,142
  • 6
  • 39
  • 67