0

I am trying to get the state of a Switch widget. To do this I create a new variable like so : Switch notifSwitch = findViewById(R.id.notif_switch).

However that does not work because now notifSwitch is null and casting setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() gets me a java.lang.NullPointerException.

I suspect it has to do with the fact that the widget with the 'notif_switch' id (the Switch that I am trying to get the value of) is not (directly) in activity_main.xml, which is the layout I am passing to setContentView at the beginning of my onCreate method because if I add setContentView(R.layout.line_notif); before the Switchdeclaration, the code works fine. The app only consists of what is in the line_notif.xmllayout, which is only the Switch and a TextView, but at least I don't have any errors and I am able to get the state of the Switch widget.

I do not know how to access the widget from my MainActivity.javafile and cannot find a way to do so. I tried looking at as many posts as possible before making my own. I am sorry if I missed one that answers my question but I just cannot find a way to solve this problem and would really appreciate the help.

Thank you.

MainActivity.java:

...
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private MainActivity activity;
    private boolean notificationsOn=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.activity = this;

        ...

        // HERE IS THE PROBLEM

        Switch notifSwitch = findViewById(R.id.notif_switch); // notifSwitch = null
        // Error on next line
        notifSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    notificationsOn = true;
                    Toast.makeText(getApplicationContext(), "Notifications enabled", Toast.LENGTH_SHORT).show();
                } else {
                    notificationsOn = false;
                    Toast.makeText(getApplicationContext(), "Notifications disabled", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
...

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:background="@color/colorPrimary"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        android:background="@color/colorPrimary"/>

</android.support.v4.widget.DrawerLayout>

activity_main_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view"
    ...>

    ...

    <item
        android:id="@+id/nav_notifications"
        app:actionLayout="@layout/line_notif"
        android:enabled="true"
        tools:ignore="MenuTitle" />

    ...

</menu>

line_notif.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/line_notif"
    android:background="@android:color/transparent">

    ...

    <Switch
        android:id="@+id/notif_switch"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="end"
        android:theme="@style/SwitchTheme"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:paddingTop="15dp"/>

</RelativeLayout>

Full error :

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projectname/com.example.projectname.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
hlbak
  • 27
  • 7
  • `notif_switch` should be in your `activity_main.xml` or if it's available in other layout then that layout must be included in `activity_main.xml`. Post your `activity_main.xml` file – Ajay Mehta Apr 19 '19 at 12:40
  • Could you please share your .xml files to get insights – Jasurbek Apr 19 '19 at 12:41
  • Just added the .xml files – hlbak Apr 19 '19 at 12:51
  • @Zoe Okay, I understand, I'm removing it, sorry I didn't know. Thanks for the welcome! – hlbak Apr 19 '19 at 12:53
  • If you will find your view inside onCreateOptionsMenu() method. Then you can get that Switch but checkChange event not firing. I was trying for the same. Refer this link for more help: https://stackoverflow.com/questions/32091709/how-to-get-set-action-event-in-android-actionbar-switch – Ajay Mehta Apr 19 '19 at 14:00

1 Answers1

0

I suspect it has to do with the fact that the widget with the 'notif_switch' id (the Switch that I am trying to get the value of) is not (directly) in activity_main.xml, which is the layout I am passing to setContentView at the beginning of my onCreate method

You're right, that's the issue. I suggest you to read this post on how to create widgets. You'll learn that the components allowed in a widget are limited and so your interaction with them.

devgianlu
  • 1,547
  • 13
  • 25