1

I'm have some problem about return value from onClick method In DialogInterface.OnClickListener(). Can I return string form edittext in dialog.When I call this method in one time without assign it to other var later.

//Exam Code
public String getPhoneNumber(){
        String phoneNumber = "";

        AlertDialog.Builder alert = new AlertDialog.Builder(context);
        alert.setTitle("Please input phone number");
        alert.setMessage("ex. 66898765432");
        final EditText phoneNumberEditText = new EditText(context);
        phoneNumberEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        alert.setView(phoneNumberEditText);


        alert.setPositiveButton("Submit",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    phoneNumber = phoneNumberEditText.getText().toString();
                {
        });

        alert.show();

        return phoneNumber;
}

in exam code it will return "" back .How I solve this problem.

Thank for all answer :)

user1181926
  • 11
  • 1
  • 2

2 Answers2

2

Your problem is that you are trying to return a value from the OnClickListener. The listener is supposed to wait for use action whereas the remaining code runs sequentially. You need to pass the value from the OnClickListener to some other method or to a global variable.

See this for a discussion on various ways to achieve this.

Community
  • 1
  • 1
Saad Farooq
  • 13,172
  • 10
  • 68
  • 94
  • +1, this is the correct solution. Your method returns immediately, before phone number has been set. Then, some time in the future, phone number is set to a value but never read after that point. – devunwired Jun 04 '12 at 16:22
-1

I'm not sure if this is a side effect of your formatting or the way your code is structured, but change your alert.setPositiveButton.. section to the following:

alert.setPositiveButton("Submit",new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      phoneNumber = phoneNumberEditText.getText();
    }
  });

Remember that phoneNumberEditText.getText() already returns a String, so you don't need .toString() as well. This should work just fine if you've entered numbers in your AlertDialog. Here's a clean example you can use.

Marvin Pinto
  • 30,138
  • 7
  • 37
  • 54
  • That's not true. The `getText()` method of any `TextView` returns a `CharSequence`, so it either must be cast or call the `toString()` method to pass it into a `String` variable. – devunwired Jun 04 '12 at 16:21