Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid - how can an Activity get user entered text from a Dialog
    primarykey
    data
    text
    <p>I thought this would be easy but its eluding me. I have an Activity that displays a custom dialog that allows the user to enter some text and then has OK and Cancel button defined. I display it using show(). But I can't figure out how to get the value back from the Dialog.</p> <p>I'm using a custom dialog because its doing some validation of the text entry. I guess I could change it to derive from Activity and then display it using startActivityForResult but - at least based on my old windows programming days - I thought getting a user entered value back from an Android dialog would be easy. </p> <p>Am I overlooking some type of call back or listener mechanism?</p> <p>I even tried this as a simple solution but its not letting me assign to value (1) unless its modifier is set to final and then (2) if I say ok to make it final, won't let me assign to it because "the final local variable value cannot be assigned, since it is defined in an enclosing type"</p> <pre><code> String value; final EditText input = (EditText)findViewById(R.id.theText); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(input); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { value = input.getText().toString(); dialog.dismiss(); } }); builder.show(); </code></pre> <p>[EDIT updated for solution]============================</p> <p>The main thing I ended up doing was adding the ability to pass a Handler to the dialog. In the dialog class I added:</p> <pre><code> private Handler clientHandler = null; public void AddHandler(Handler client) { this.clientHandler = client; } </code></pre> <p>And updated the Dialog's OK button click:</p> <pre><code> /** * The user pressed the OK button * @param v */ public void okClick(View v) { // save the entered string this.tag = this.tagEditText.getText().toString(); if ( null != this.clientHandler ) { // Notify the client to update itself this.clientHandler.sendMessage( clientHandler.obtainMessage()); } cancel(); } </code></pre> <p>Then in the Activity's onCreate() that displays the Dialog I added:</p> <pre><code> tagDialog = new tagDialog(this); tagHandler = new Handler() { @Override public void handleMessage(Message msg) { tag = tagDialog.tag; } }; tagDialog.AddHandler(tagHandler); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload