Question

I created an AlertDialog such that when you press a Button, the Dialog pops up and a layout appears with EditTexts. However, I created the layout in the actual code rather than in the xmlfile. For some reason, when the AlertDialog pops up, it's not able to find the EditText field and gives me a NullPointerException.

//private Lecture lecture;
private LectureManager lectureManager;

public void addWork(View view) {

    LinearLayout layout = new LinearLayout(this);
    EditText weight = new EditText(this);
    EditText mark = new EditText(this);

    mark.setInputType(InputType.TYPE_CLASS_NUMBER);
    weight.setInputType(InputType.TYPE_CLASS_NUMBER);

    weight.setId(99);
    mark.setId(100);

    layout.addView(mark);
    layout.addView(weight);

    AlertDialog.Builder addwork = new AlertDialog.Builder(this);
    addwork.setView(layout);

    addwork.setPositiveButton("Add", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            EditText eweight = (EditText) findViewById(99);
            EditText emark = (EditText) findViewById(100);
            String coursename = ecoursename.getText().toString();

And for some reason, I'm getting a NullPointerException at the "EditText weight" line. I believe that maybe it's not finding anything with ID 99 and that the EditText might be out of scope? Thanks in advance!

Was it helpful?

Solution

Actually, when you make these calls:

EditText eweight = (EditText) findViewById(99);
EditText emark = (EditText) findViewById(100);

you're calling the findViewById() method of your Activity, not the AlertDialog. In order to retrieve the views from the Dialog, you can use something like this, inside onClick():

EditText eweight = (EditText) ((AlertDialog)dialog).findViewById(99);
EditText emark = (EditText) ((AlertDialog)dialog).findViewById(100);

Hope this helps.

OTHER TIPS

Try this..

Use final for both EditText while initilization like below

final EditText weight = new EditText(this);
final EditText mark = new EditText(this);

Then you can get the text from EditText in PositiveButton

String weight_txt = weight.getText().toString().trim();
String mark_txt = mark.getText().toString().trim();

No need to set id for EditText also no need findViewById.

i think you need to do this

EditText eweight = (EditText) view.findViewById(99);

and view is , what you have passed in your addWork() method parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top