2015-10-11 46 views
0

当我开始我的setting活动时,我似乎正在得到一个NULL POINTER异常。我正在做的是试图检查一个RadioGroups单选按钮是否改变,以及当我初始化一个RadioGroup对象时它会崩溃。找到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

不能使用findViewById初始化这样的成员字段:

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

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