且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

开关(按键)抛出NullPointerException异常

更新时间:2023-11-19 12:34:46

由ρяσѕρєяK'按照答案,但改变code他的下面一行:

 菜单项项= menu.findItem(R.id.switch_button);
 

这样:

 菜单项项= menu.findItem(R.id.myswi​​tch); //该ID被改变!
 

这应该摆脱NullPointerException异常的,希望这有助于:)

所以,你应该是这样的:

  @覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_minepedia_main);
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    MenuInflater充气= getMenuInflater();
    inflater.inflate(R.menu.main_actions,菜单);

    菜单项项= menu.findItem(R.id.myswi​​tch);
    switchButton =(开关)item.getActionView();

    switchButton.setOnCheckedChangeListener(新CompoundButton.OnCheckedChangeListener({

    @覆盖
    公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){

    //下面是一个局部布尔变量
            如果(器isChecked){
                ONLINE_MODE_ENABLED = TRUE;
            } 其他 {
                ONLINE_MODE_ENABLED = FALSE;
            }

        }
    });

    返回super.onCreateOptionsMenu(菜单);
}
 

此外改变这一行:

 安卓actionLayout =@布局/ switch_layout
 

这样:

 安卓actionViewClass =android.widget.Switch
 

这是你的菜单XML中。如果您应用的变化,那么你使用的是由机器人提供的开关按钮和必须的工作。

I know this question already exists, but I tried serveral solutions and none worked for me.

In my case, I need a Switch Button in the ActionBar.

  • I tried to manually add a minSdk Verision
  • I tried to use the id of the item in the defined xml

Edit: The exception-point in the code is marked with a comments. It's in the mainactivity. :)

Here is some of my code:

mainactivity:

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

        switchButton = (Switch) findViewById(R.id.switch_button);

        //The following line throws an exception, because switchButton
        //is null, even though I tried to take it on the upper line.
        switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        //The following is a local boolean variable
                if (isChecked) {
                    ONLINE_MODE_ENABLED = true;
                } else {
                    ONLINE_MODE_ENABLED = false;
                }

            }
        });
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; --> main_actions.xml
    getMenuInflater().inflate(R.menu.main_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

mainactivity_layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".Minepedia_main">

    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_centerInParent="true"
        android:gravity="center" >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/items_button"
            android:onClick="startItemsMenu" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/about_button"
            android:onClick="startAboutScreen" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="bottom"
            android:paddingTop="50dp"
            android:orientation="vertical">
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/update_offline_button"
                android:onClick="startOfflineUpdate"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/offline_sync_info"
                android:id="@+id/textView"
                android:layout_gravity="center_horizontal" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

main_actions.xml (menu):

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
    <!-- Search, should appear as action button -->
    <item
        android:id="@+id/myswitch"
        android:title=""
        android:showAsAction="always"
        android:actionLayout="@layout/switch_layout"
        />
</menu>

switch_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Switch
        android:id="@+id/switch_button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text=""
        android:textOff="Offline"
        android:textOn="Online"/>
</RelativeLayout>

Stacktrace:

08-20 17:45:52.902    5534-5534/com.nubage.minepedia E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.nubage.minepedia, PID: 5534
    java.lang.NullPointerException
            at com.nubage.minepedia.Minepedia_main.onCreateOptionsMenu(Minepedia_main.java:63)
            at android.app.Activity.onCreatePanelMenu(Activity.java:2538)
            at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:489)
            at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:853)
            at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:273)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
            at android.view.Choreographer.doCallbacks(Choreographer.java:574)
            at android.view.Choreographer.doFrame(Choreographer.java:543)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5081)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
            at dalvik.system.NativeStart.main(Native Method)

Follow the answer by 'ρяσѕρєя K' but change his following line of code:

MenuItem item = menu.findItem(R.id.switch_button);

to this:

MenuItem item = menu.findItem(R.id.myswitch); //the id was changed!

That should get rid of the NullPointerException, hope this helps :)

So you should have something like this:

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

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_actions, menu);

    MenuItem item = menu.findItem(R.id.myswitch);
    switchButton = (Switch)item.getActionView();

    switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener({

    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    //The following is a local boolean variable 
            if (isChecked) {
                ONLINE_MODE_ENABLED = true; 
            } else { 
                ONLINE_MODE_ENABLED = false; 
            } 

        } 
    }); 

    return super.onCreateOptionsMenu(menu);
}

Additionally change this line:

android:actionLayout="@layout/switch_layout" 

to this:

android:actionViewClass="android.widget.Switch"

That is within your menu xml. If you apply that change then you are using the switch button provided by android and that must work.