2016-07-09 28 views
0

致使用複選框時:在一個空對象引用的NullPointerException在機器人

此嘗試調用虛擬方法「無效android.widget.CheckBox.setChecked(布爾值)」:顯示java.lang.NullPointerException是我無法弄清楚爲什麼會發生的錯誤。

這裏是我java類

public class PopUpInfoActivity extends Activity { 
static final String PREFS = "preference_file"; 

@Override 
public void onCreate(Bundle state){ 
    super.onCreate(state); 

    CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox); 
    chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false)); 

    chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){ 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      //store isChecked to Preferences 
      SharedPreferences settings = getSharedPreferences(PREFS,0); 
      SharedPreferences.Editor editor = settings.edit(); 
      editor.putBoolean("isChecked", false); 

      PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply(); 
     } 
    }); 
} 
} 

在我進口android.widget.CheckBox

,這是我xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="200dp" 
    android:scaleType="centerInside" 
    android:src="@drawable/legenda" /> 

<CheckBox 
    android:id="@+id/dontshow_checkbox" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/dont_show" 
    android:textAllCaps="true" 
    android:fontFamily="sans-serif" 
    android:textStyle="bold" 
    android:layout_gravity="center"/> 

</LinearLayout> 

我真的很感激,如果你能幫助我解決這個錯誤!

+0

setContentView(R.layout.xmllayout); – Androider

回答

1

您已經得到了正確的id,但是您錯過了一條非常重要的行 - setContentView。該行將xml與Activity的視圖綁定在一起,它就是用於findViewById的視圖。將此行添加到您的onCreate

@Override 
public void onCreate(Bundle state){ 
    super.onCreate(state); 
    setContentView(R.layout.name_of_the_xml); 

然後剩下的代碼。一定要提供一個正確的XML名稱。

+1

謝謝你的答案!多麼愚蠢的錯誤!不敢相信我看不到! – Daniele

+0

不客氣。啊,我知道,有時候需要別人來看看你錯過了什麼。 D經常發生在我身上:D – Vucko