Android:从DialogFragment传回用户输入会导致NullPointerException

时间:2016-04-12 16:51:32

标签: java android nullpointerexception

所以我查看了Dialogs Link的Android教程。 并决定制作一个自定义对话框,询问用户要连接的主机,用户名和密码。我不想连接到Dialog类中的主机,所以我需要将字符串传递回主要活动。我尝试使用接口,就像在教程中一样,但是当我想在访问EditText的主要活动中处理事件时,我得到一个NullPointerException。我确定有一个简单的解决方法或我犯了一些其他愚蠢的错误。请帮忙!

对话类:

public class ConnectionDialog extends DialogFragment {

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

// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;

// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
@Override
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 = (NoticeDialogListener) activity;
    } catch (ClassCastException e) {
        // The activity doesn't implement the interface, throw exception
        throw new ClassCastException(activity.toString()
                + " must implement NoticeDialogListener");
    }
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    final 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.connection_dialog, null))
            // Add action buttons
            .setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    mListener.onDialogPositiveClick(ConnectionDialog.this);
                    // sign in the user ...
                }
            })
            .setNegativeButton(R.string.abort, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    mListener.onDialogNegativeClick(ConnectionDialog.this);
                    //LoginDialogFragment.this.getDialog().cancel();
                }
            });
    return builder.create();

}
}

主要活动:

public class MainActivity extends FragmentActivity implements ConnectionDialog.NoticeDialogListener {

public void showConnectionDialog() {
    // Create an instance of the dialog fragment and show it
    DialogFragment dialog = new ConnectionDialog();
    dialog.show(getFragmentManager(), "Connection Dialog");
}

public void toast(String message){
    Context context = getApplicationContext();
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, message, duration);
    toast.show();
}

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

}

@Override
public void onDialogPositiveClick(DialogFragment dialog) {
    EditText editHost = (EditText)dialog.getView().findViewById(R.id.dialog_host);
    EditText editUser = (EditText)dialog.getView().findViewById(R.id.dialog_user);
    EditText editPassword = (EditText)dialog.getView().findViewById(R.id.dialog_password);
    String host = editHost.getText().toString();
    String user = editUser.getText().toString();
    String password = editPassword.getText().toString();

    dialog.dismiss();
}

@Override
public void onDialogNegativeClick(DialogFragment dialog) {
    toast("cancled");
    dialog.dismiss();
    // User touched the dialog's negative button
}
public void connect(View view){
    showConnectionDialog();
}
}

非常感谢!

编辑:

的NullPointerException

04-12 18:52:00.278 5216-5216/com.example.josias.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.josias.myapplication, PID: 5216
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                at com.example.josias.myapplication.MainActivity.onDialogPositiveClick(MainActivity.java:44)
                                                                                at com.example.josias.myapplication.ConnectionDialog$2.onClick(ConnectionDialog.java:54)
                                                                                at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:153)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

3 个答案:

答案 0 :(得分:2)

是的你可以。 您的界面将如下所示,

public interface NoticeDialogListener {
    public void onDialogPositiveClick(DialogFragment dialog);
}

将这样的DialogFragment实例传递给接口,在onClick()方法的正按钮中。

.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    noticeDialogListener.onDialogPositiveClick(NoticeDialog.this);
                }
            })

接下来在您的MainActivity中 - 您可以将您已显示为表单的DialogFragment的每个字段。在您将在MainActivity中覆盖的接口方法中,定义如下,

@Override
public void onSaveButtonClick(DialogFragment dialog) {
 ......

    EditText field1= (EditText) dialog.getDialog().findViewById(R.id.field1);
    EditText field2= (EditText) dialog.getDialog().findViewById(R.id.field2);
....
}

然后您可以获取文本并按照您的要求工作。有关更多信息,您可以重新考虑这个:https://www.youtube.com/watch?v=a0T--DfR48A这里一切都得到了解释......

答案 1 :(得分:0)

切换接口以传递String值,而不是传递整个对话框。

为了帮助您入门,请执行以下操作

public interface NoticeDialogListener {
    public void onDialogPositiveClick(String host, String user, String pass);
    public void onDialogNegativeClick();
}
final 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
View dialogView = inflater.inflate(R.layout.connection_dialog, null);

final EditText editHost = (EditText)dialogView.findViewById(R.id.dialog_host);
final EditText editUser = (EditText)dialogView.findViewById(R.id.dialog_user);
final EditText editPassword = (EditText)dialogView.findViewById(R.id.dialog_password);

builder.setView(dialogView)
        // Add action buttons
        .setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                String host = editHost.getText().toString();
                String user = editUser.getText().toString();
                String pass = editPassword.getText().toString();

                mListener.onDialogPositiveClick(host, user, pass);
            }
        })
        // set null to dismiss dialog
        .setNegativeButton(R.string.abort, null);
return builder.create();

答案 2 :(得分:0)

您应该使用:

dialog.getDialog()

而不是:

dialog.getView()