当我开始我的setting
Activity 时,我似乎遇到了空指针异常。我所做的只是尝试检查 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>
最佳答案
您不能使用 findViewById
来初始化成员字段,如下所示:
public class Setting extends Main {
RadioGroup appTileTheme = (RadioGroup) findViewById(R.id.radGroupTileColour);
// ...
您只能在调用 onCreate
后(或在 onCreate
内部)使用 findViewById
。
关于java - 查找RadioGroup时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063058/