2013-08-22 3 views
0

Привет У меня есть checbox и хотите сделать что-то, если флажок установлен, но я получаю ошибку NullPointerException, когда я проверяю, если его проверить с помощью если заявления:андроида флажок возвращает java.lang.NullPointerException

if (chkChickenBreast.isChecked()){ 
    \\Do Something; 
} 

у меня есть это в моем receiptActivity.java:

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

    Double priceChickenBreast = 30.00; 

    LinearLayout receiptLayout = (LinearLayout)findViewById(R.id.receiptMainLinearLayout); 
    TextView menuChickenBreast = new TextView(this); 

    final CheckBox chkChickenBreast = (CheckBox) findViewById(R.id.checkBox1); 


    try{ 
     if (chkChickenBreast.isChecked()){ 
      menuChickenBreast.setText("Chicken Breast  Php 30.00"); 
      receiptLayout.addView(menuChickenBreast); 

     } 
    }catch(Exception e){ 
     menuChickenBreast.setText(e.toString()); 
     receiptLayout.addView(menuChickenBreast); 
    } 

} 

}

Мой order.xml:

<LinearLayout 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:background="#99FF50" 
android:gravity="top" 
android:orientation="vertical" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity" > 

<ScrollView 
    android:id="@+id/scrollView_Main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TableLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

     <TableRow 
      android:id="@+id/tableRow_Menu1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" > 

      <TextView 
       android:id="@+id/textView_MenuTitle" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:gravity="center" 
       android:text="@string/order_title" 
       android:textAppearance="?android:attr/textAppearanceMedium" /> 

     </TableRow> 

     <TableRow 
      android:id="@+id/tableRow2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" > 

      <CheckBox 
       android:id="@+id/checkBox1" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center_vertical" 
       android:text="@string/menu_one" 
       android:checked="false" 
       android:textSize="12sp" /> 

      <ImageView 
       android:id="@+id/imageView_Menu1" 
       android:layout_width="50dp" 
       android:layout_height="50dp" 
       android:layout_marginLeft="50dp" 
       android:contentDescription="@string/menu_one" 
       android:src="@drawable/chickenbreast" /> 

     </TableRow>    

    </TableLayout> 

</ScrollView> 

и мой Receipt.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/receiptMainLinearLayout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#99FF50" 
android:gravity="top" 
android:orientation="vertical" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context=".MainActivity" > 

<TextView 
    android:id="@+id/textViewReceiptTitle" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:text="@string/receipt_title" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

+0

Вы уверены, что ошибка в этой строке «если (chkChickenBreast.isChecked()) {»? –

+0

Вы забыли один '' в конце вашего файла макета – Sw4Tish

+0

Проверьте свой xml-файл, вам не хватает – Jilberta

ответ

0

Может быть, ваша проблема не в CheckBox

Linear Layout ид

LinearLayout receiptLayout = (LinearLayout)findViewById(R.id.receiptMainLinearLayout); 

Вы используете отдельный файл XML затем использовать Inflater концепцию

попробуйте этот код

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Double priceChickenBreast = 30.00; 

     LinearLayout receiptLayout=(LinearLayout) getLayoutInflater().inflate(R.layout.receipt, null); 

     TextView menuChickenBreast = new TextView(this); 

     CheckBox chkChickenBreast = (CheckBox) findViewById(R.id.checkBox1); 

     if (chkChickenBreast.isChecked()) { 
      menuChickenBreast.setText("Chicken Breast  30.00"); 
      receiptLayout.addView(menuChickenBreast); 
     } 

    } 
+0

в другом XML-файле, называемом order.xml. – PaulPolon

+0

Добавить атрибут id в ваш макет android: id = "@ + id/receiptMainLinearLayout" – Venky

+0

затем использовать концепцию надувателя – Venky

0

Попытка установить флажок до некоторого значения т.е. истина или ложь, прежде чем проверить его в случае. Поместите это в свой xml внутри android: checked = "true".

+0

Я попытался вставить 'android: checked =" false "', но она по-прежнему дает мне ошибку – PaulPolon

+0

вы можете попытаться положить ваши, если внутри этого chekbox.setOnCheckedChangeListener (новый OnCheckedChangeListener() { \t общественного недействительными onCheckedChanged (CompoundButton arg0, логическое arg1) { \t} }); – Shrikant

0

Вы пропустили

</TableRow> 

в файле макета

Попробуйте

chkChickenBreast.setChecked="true" 
+0

@ Sw4Tish thnaks..but ошибка все еще сохраняется - PaulPolon 2 мин назад – Sw4Tish

0
LinearLayout receiptLayout = (LinearLayout)findViewById(R.id.receiptMainLinearLayout); 

Я не нахожу R.id.receiptMainLinearLayout в вашем XML. Так null pointer exception произошло , когда вы звоните receiptLayout.addView(menuChickenBreast);

Смежные вопросы