在isChecked()上获取NullPointerException以获取DialogFragment中的复选框

时间:2013-12-28 19:09:15

标签: android nullpointerexception findviewbyid dialogfragment ischecked

我在登录DialogFragment中有一个复选框,我想用它来检查是否应该将输入的用户名添加到首选项中。但是当我使用复选框的isChecked()方法时,我得到一个NullPointerException。我添加了一个try / catch时钟,然后进一步尝试添加复选框的toString输出的Log.d,再次出现NullPointerException。因此,虽然很明显代码似乎没有认识到当前范围中复选框的存在,但我无法弄清楚我看到了什么。它允许我使用findViewById创建一个没有错误的CheckBox。感谢。

登录DialogFragment的源代码:

public class LoginDialogFragment extends DialogFragment {


public interface LoginDialogListener {
    public void onDialogPositiveClick(DialogFragment dialog);
    public void onDialogNegativeClick(DialogFragment dialog);
}

LoginDialogListener mListener;

public void onAttach(Activity activity) {
    super.onAttach(activity);
    // Verify that the host activity implements the callback interface
    try {
        // Instantiate the NoticeDialogListener so we can send events to the host
        mListener = (LoginDialogListener) activity;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
    }
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = getActivity().getLayoutInflater();

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.login_dialog, null))
    // Add action buttons
           .setPositiveButton("Login", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                // Send the positive button event back to the host activity
                   CheckBox loginCheckBox = 
(CheckBox)getActivity().findViewById(R.id.input_chkbox);
                   try{
                       if(loginCheckBox.isChecked() == true){

mListener.onDialogPositiveClick(LoginDialogFragment.this);
                       }else{

mListener.onDialogNegativeClick(LoginDialogFragment.this);
                       }
                   }catch(Exception e){
                       Log.d(null, e.toString());
                       Log.d(null, loginCheckBox.toString());  // got 
nullPointerException again when I added this line in catch block.
                       Toast eToast = Toast.makeText(getActivity(), "error in: 
LoginDialogFragment.setPosButton.onClick", Toast.LENGTH_LONG);
                       eToast.show();
                   }
               }
           })    

对话框片段的父活动的源代码:

public class UsingPreferencesActivity
extends FragmentActivity
    implements LoginDialogFragment.LoginDialogListener{

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.main);
    this.showLoginDialog();

}

public void showLoginDialog() {
    // Create an instance of the dialog fragment and show it
    DialogFragment dialog = new LoginDialogFragment();
    dialog.show(getSupportFragmentManager(), "LoginDialogFragment");
}

public void onDialogPositiveClick(DialogFragment dialog) {
    Toast toast = Toast.makeText(getBaseContext(), "OK", Toast.LENGTH_LONG);
    toast.show();

}

public void onDialogNegativeClick(DialogFragment dialog) {
    Toast toast = Toast.makeText(getBaseContext(), "Cancel", 
Toast.LENGTH_LONG);
    toast.show();
}

public void onClickLoad(View view){
    Intent i = new Intent("com.example.homework09.AppPreferenceActivity");
    startActivity(i);
}


public void onClickDisplay(View view){
    SharedPreferences appPrefs = 
getSharedPreferences("com.example.homework09_preferences",MODE_PRIVATE);
    DisplayText(appPrefs.getString("editTextPref", ""));
}


public void onClickModify(View view){
    SharedPreferences appPrefs = 
getSharedPreferences("com.example.homework09_preferences", MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = appPrefs.edit();
    prefsEditor.putString("editTextPref", 
((EditText)findViewById(R.id.etNewUsername)).getText().toString());
    prefsEditor.commit();
    DisplayText(appPrefs.getString("editTextPref", ""));
}


public void onClickReset(View view){

    SharedPreferences appPrefs = 
getSharedPreferences("com.example.homework09_preferences", MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = appPrefs.edit();
    prefsEditor.putString("editTextPref", " ");
    prefsEditor.commit();
    DisplayText(appPrefs.getString("editTextPref", ""));
}


private void DisplayText(String str){
    Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
    TextView textView = (TextView)findViewById(R.id.tvUsername);
    textView.setText(str);
}

}

DialogFragment(login_dialog.xml)的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >


<EditText 
    android:id="@+id/input"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="[Enter username here]"/>

<CheckBox 
    android:id="@+id/input_chkbox"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Save Username?"
    android:defaultValue="false"
    />

</LinearLayout>

1 个答案:

答案 0 :(得分:2)

替换

CheckBox loginCheckBox = (CheckBox)getActivity().findViewById(R.id.input_chkbox);

AlertDialog alertDialog = (AlertDialog)dialog;
CheckBox loginCheckBox = (CheckBox)alertDialog.findViewById(R.id.input_chkbox);

此处复选框是Dialog not Activity的一部分。所以你必须使用对话框引用来获取Checkbox