Return to Android
Haven't done native Android development in a while, do I still know Java?
A student had mentioned an interest in Mobile App Development, so decided to redownload Android Studio and create some dummy application just to refamiliarize myself with the ecosystem. So after the GBs of downloads, my goal was to create my go-to application: A number guessing game that allows minimum and maximum number customization. To go the extra mile, decided to show a random XKCD comic when the user successfully guesses the correct number.
The layout I decided to go with:
- ScrollView
- LinearLayout (Vertical)
- TextView (Message Output)
- LinearLayout (Horizontal)
- LinearLayout (Horizontal)
- ImageView
- LinearLayout (Vertical)
The Code
Now the actual code was quite simple, I kept track of only a few state variables:
private int min = 0;
private int actual = 0;
private int max = 0;
private int count = 0;
private int state = 0;
private long started = 0;
with the only one needing explanation would be state
, which was a Enum representing the state of the game:
PLAYING, WON, OVER
Starting off I needed to handle the game starting when the Start/Reset Button was pressed, so my method started a new game if the state wasn't OVER
, which consisted of actually pulling in the information from the numeric EditTexts, generating the random number between them, and finally updating the UI elements - text, enabled state, etc - and focusing the guess ExitText.
At this point the Guess Button only needed to pull the int
from the guess EditText, and handle it accordingly:
- If out of range, too high, or too low, create a toast stating so
- Otherwise add a successful message, update the UI accordingly, and start the AsyncTask to fetch the random XKCD comic image.
Lastly was handling the game resetting, which did the same no matter if won or not, except for the message getting the correct number appended if the user had not won.
AsyncTask Fetching
For the uninitiated, the XKCD comic has a simple JSON API, so I picked a number between 1
and the number of current comics, then did the needed to fetch and parse said JSON, then returned a Bitmap
, which after the background task I set the ImageView bitmap to
Improved UX
At this point the user had to manually switch between fields, hit buttons, and retype guesses - all of which could be streamlined. Starting with switching between fields, I added some TextView.OnEditorActionListener
s to each input, with the minimum focusing the maximum, the maximum starting the game, and the guess making a guess. Next was to make re-guessing easier, so whenever the guess is invalid I'd additional select all the text within the guess EditText.
Last but not least was handling the back button, making it automatically cancel/reset the game on press.