找到RadioGroup时获取空指针异常

时间:2015-10-11 08:36:51

标签: java android

当我开始setting活动时,我似乎得到了一个N​​ULL POINTER异常。我正在做的就是尝试检查RadioGroups单选按钮是否发生变化,当我初始化一个RadioGroup对象时它会崩溃。

Logcat消息:

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

at com.example.pckg.Setting.<init>(Setting.java:14)

这是我的Java代码:

import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;


public class Setting extends Main {
    // Radio Groups declaration LINE 14 IS BELOW V
    RadioGroup appTileTheme = (RadioGroup) findViewById(R.id.radGroupTileColour);

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

        checkIfThemeChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    public void checkIfThemeChanged() {

        appTileTheme.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(RadioGroup group, int checkedId) {
//              Log.d("chk", "id" + checkedId);

                if (checkedId == R.id.radTheme1) {
                    setThemeSharedPreferences(1);

                } else if (checkedId == R.id.radTheme2) {
                    setThemeSharedPreferences(2);
                }

            }

        });
    }

这是我的XML:

<TextView
        android:id="@+id/txtGridTileColour"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Grid Tile Colour"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:layout_marginTop="15dp" />

    <RadioGroup
        android:id="@+id/radGroupTileColour"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal" >

        <RadioButton
            android:id="@+id/radTheme1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Normal" />

        <RadioButton
            android:id="@+id/radTheme2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Cool Gradient" />
    </RadioGroup>

1 个答案:

答案 0 :(得分:1)

您无法使用findViewById初始化成员字段,如下所示:

public class Setting extends Main {
    RadioGroup appTileTheme = (RadioGroup) findViewById(R.id.radGroupTileColour);
    // ...

您只能在findViewById被调用后(或onCreate内)使用onCreate