开关(按键)抛出NullPointerException异常抛出、按键、异常、NullPointerException

2023-09-12 03:27:33 作者:ゞ孩子、乖乖

我知道这个问题已经存在,但我想serveral的解决方案,并没有为我工作。

在我的情况,我需要一个开关按钮的动作条。

我试图手动添加minSdk Verision 我试图用项目的id在定义的XML

编辑:异常点在code标有注释。它在mainactivity。 :)

下面是我的一些code:

mainactivity:

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

        switchButton =(开关)findViewById(R.id.switch_button);

        //下面这行抛出一个异常,因为switchButton
        //为空,即使我试图把它的上线。
        switchButton.setOnCheckedChangeListener(新CompoundButton.OnCheckedChangeListener(){

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

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

            }
        });
    }

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单; - > main_actions.xml
    。getMenuInflater()膨胀(R.menu.main_actions,菜单);
    返回super.onCreateOptionsMenu(菜单);
}
 
热门家用A级车推荐 C4L 轩逸 科鲁兹 思域

mainactivity_layout:

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:以下属性来=@扪/ activity_horizo​​ntal_margin
    机器人:paddingRight =@扪/ activity_horizo​​ntal_margin
    机器人:paddingTop =@扪/ activity_vertical_margin
    机器人:paddingBottom会=@扪/ activity_vertical_margin
    工具:上下文=Minepedia_main。>

    <的LinearLayout
        机器人:layout_width =200dp
        机器人:layout_height =match_parent
        机器人:方向=垂直
        机器人:layout_centerInParent =真
        机器人:重力=中心>
        <按钮
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:文本=@字符串/ items_button
            机器人:的onClick =startItemsMenu/>
        <按钮
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:文本=@字符串/ about_button
            机器人:的onClick =startAboutScreen/>
        <的LinearLayout
            机器人:layout_width =match_parent
            机器人:layout_height =WRAP_CONTENT
            机器人:重力=底
            机器人:paddingTop =50dp
            机器人:方向=垂直>
            <按钮
                机器人:layout_width =match_parent
                机器人:layout_height =WRAP_CONTENT
                机器人:文本=@字符串/ update_offline_button
                机器人:的onClick =startOfflineUpdate/>
            <的TextView
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:textAppearance =机器人:ATTR / textAppearanceSmall
                机器人:文本=@字符串/ offline_sync_info
                机器人:ID =@ + ID / TextView的
                机器人:layout_gravity =center_horizo​​ntal/>
        < / LinearLayout中>
    < / LinearLayout中>
< / RelativeLayout的>
 

main_actions.xml(菜单):

 <菜单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:yourapp =htt​​p://schemas.android.com/apk/res-auto>
    <  - !搜索,应显示为操作按钮 - >
    <项目
        机器人:ID =@ + ID /是myswi​​tch
        机器人:标题=
        机器人:showAsAction =总是
        机器人:actionLayout =@布局/ switch_layout
        />
< /菜单>
 

switch_layout.xml:

 < XML版本=1.0编码=UTF-8&GT?;
< RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
    <开关
        机器人:ID =@ + ID / switch_button
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =match_parent
        机器人:文本=
        机器人:textOff =离线
        机器人:纹元=在线/>
< / RelativeLayout的>
 

堆栈跟踪:

  08-20 17:45:52.902 5534-5534 / com.nubage.minepedia E / AndroidRuntime:致命异常:主要
    工艺:com.nubage.minepedia,PID:5534
    显示java.lang.NullPointerException
            在com.nubage.minepedia.Minepedia_main.onCreateOptionsMenu(Minepedia_main.java:63)
            在android.app.Activity.onCreatePanelMenu(Activity.java:2538)
            在com.android.internal.policy.impl.PhoneWindow。preparePanel(PhoneWindow.java:489)
            在com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:853)
            在com.android.internal.policy.impl.PhoneWindow $ 1.运行(PhoneWindow.java:273)
            在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:761)
            在android.view.Choreographer.doCallbacks(Choreographer.java:574)
            在android.view.Choreographer.doFrame(Choreographer.java:543)
            在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:747)
            在android.os.Handler.handleCallback(Handler.java:733)
            在android.os.Handler.dispatchMessage(Handler.java:95)
            在android.os.Looper.loop(Looper.java:136)
            在android.app.ActivityThread.main(ActivityThread.java:5081)
            在java.lang.reflect.Method.invokeNative(本机方法)
            在java.lang.reflect.Method.invoke(Method.java:515)
            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:791)
            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
            在dalvik.system.NativeStart.main(本机方法)
 

解决方案

由ρяσѕρєя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.