0

so I am new to programming in Android so I apologize if this is a beginner mistake, but I was programming my button to add a user to an array list with the name given in the dialog box. When I run it, everything works except when it executes users.add(new User(name)); (It returns a null pointerI'm unsure as to why this is the case. Any help would be greatly appreciated. Here is my code.

addPersonButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        final EditText input = new EditText(mainActivity);

        new AlertDialog.Builder(mainActivity)
            .setTitle("New User")
            .setMessage("What is the new user's name?")
            .setView(input)
            .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    final String name = input.getText().toString();
                    users.add(new User(name));
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    // Do nothing.
                }
            }).show();
    }
});
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
bhafenri
  • 140
  • 1
  • 1
  • 5

2 Answers2

0

i think your problem is with input in onClick method, and because input in your dialog layout not in main layout, so you must use following code:

    final String name = dialog.input.getText().toString();
    users.add(new User(name));
Shayan Pourvatan
  • 11,898
  • 4
  • 42
  • 63
0

create edittext in xml and use findViewById(R.id.edittext);

or in java

final EditText input = new EditText(MainActivity.this);

refer here

Community
  • 1
  • 1
Nambi
  • 11,944
  • 3
  • 37
  • 49