Philip
Philip

Reputation: 47

How to getText() from a TextView in an AlertDialog?

I have an AlertDialog that opens pressing a Button.

In this AlertDialog there are a button and a TextView showing a number.

I have to create a function that increments by 1 the number in the TextView when the button in the AlertDialog is pressed.

In order to do that, I wrote this into the .java file of the activity that opens the AlertDialog.

public void plus(View view)
{
    TextView total = (TextView) findViewById(R.id.Total);        
    totalP = Integer.parseInt((String)(total.getText())) + 1;
    total.setText(String.valueOf(totalP));
}

But it gives error on total.getText()

I tried to write something similar, but with the TextView into the activity, and it works fine.

I started programming Android a week ago, I'm not very good. Please, help me!

Thank you!

Upvotes: 0

Views: 354

Answers (2)

tachyonflux
tachyonflux

Reputation: 20211

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

new AlertDialog.Builder(MainActivity.this)
        .setTitle("Title")
        .setView(input)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String in = input.getText().toString();
            }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        })
        .show();

Upvotes: 0

Snake
Snake

Reputation: 14658

If your dialog variable is named diag, then try the following

TextView total = (TextView) diag.findViewById(R.id.Total);

Notice that you are calling the findViewById() on the Dialog not the Activity

Upvotes: 1

Related Questions