Search code examples
javaandroiddialoguser-input

Proper way to receive user input in Android and then continue execution


I am implementing an Interpreter for a moderately simple Pascal/BASIC-like programming language, in Android. I have finished the parser, so programs get recognized, loaded in memory and ready to execute. The language is procedural, emulating command line input/output and obviously not event-driven like Java in Android.

A sample program may look like this:

FOR i FROM 1 TO 10
    READ Name
    PRINT "User ", i, " name: ", Name
END_LOOP

Being relatively new to Android, I did not know that Android dialogs are asynchronous, and thus cannot interrupt execution, as explained in dozens of similar questions. (1), (2), (3), (4)
So, I initially thought I would implement READ commands by showing a modal Dialog. Executing code that involves reading input from the user, would require waiting for it to finish before moving on to the next line of code. But this should not be done with a dialog, as mentioned in the above posts.

I figured out that the most "appropriate" way would be to "save" the execution state of the whole program, stop execution and then start executing by loading the last state, when user inputs something from the Dialog. But this seems impossible, and way too much hassle for such a simple task. Is there an easier way?

Any suggestions are welcome.


Solution

  • I did not know that Android dialogs are asynchronous, and thus cannot interrupt execution, as explained in dozens of similar questions

    All Android UI is asynchronous.

    I initially thought I would implement READ commands by showing a modal Dialog.

    There is nothing intrinsically wrong with this. However, READ would need to suspend execution of your interpreter until the user has completed the dialog.

    Is there an easier way?

    Off the cuff...

    Step #1: Run your interpreter on a background thread.

    Step #2: Have your READ code invoke your dialog on the main application thread, then block on a Semaphore to block your background thread.

    Step #3: Have your dialog code get the results of the user input over to your interpreter by some means, then release the Semaphore when the dialog goes away.

    Step #4: Your interpreter code continues.