Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Input Dialog Return Input Value

I'm pulling my hair out over this one.

I have an app that when you press a menu item, I want it to show an input alert dialog. When the user taps "OK" then the text they've entered into the EditText in the dialog wants to be returned to be used later in the activity.

So I thought putting:

name = input.getText().toString(); //input is an EditView which is the setView() of the dialog

Inside the onClick of the "Ok" button would work but it doesn't. Eclipse tells me I cant set name inside the onClick because it isn't final, but if I change name's definition to final it can't be changed obviously and so can't be set inside the onClick().

Here is the full code for this bit:

String routeName = "";

        AlertDialog.Builder alert = new AlertDialog.Builder(this);  

        alert.setTitle("Title");  
        alert.setMessage("Message");  

        // Set an EditText view to get user input   
        final EditText inputName = new EditText(this);  
        alert.setView(inputName);  

        alert.setPositiveButton("Set Route Name", new DialogInterface.OnClickListener() {  
        public void onClick(DialogInterface dialog, int whichButton) {  
            routeName = inputName.getText().toString();  
          }  
        }); 

        alert.show();

I must be doing something really stupid here because I've googled around for ages and found no-one else with the same problem.

Can anyone please enlighten me?

Thank you for your time,

InfinitiFizz

like image 917
Infiniti Fizz Avatar asked Feb 13 '11 20:02

Infiniti Fizz


2 Answers

Indeed, you can't get to just anything inside your onClick, which is an anonymous method I presume. What you can do is get the context and find your views from there. It would look something like this:

yourButton.setOnClickListener(new View.OnClickListener() {
        public boolean onClick(View v) {
               name = findViewById(R.id.yourInputId)).getText().toString();
               return true;
        }
);

You could also use the v argument, for instance by calling v.getContext() in your listener.

like image 193
Nanne Avatar answered Sep 28 '22 06:09

Nanne


You could make routerName a member variable.

like image 38
foobaa Avatar answered Sep 28 '22 07:09

foobaa