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?