Book Image

Learning Java by Building Android Games

By : John Horton
Book Image

Learning Java by Building Android Games

By: John Horton

Overview of this book

Table of Contents (17 chapters)
Learning Java by Building Android Games
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Chapter 5


Q1) Suppose we wanted to have a quiz where the question could be about naming the president, the capital city, and so on. How would we do this with multidimensional arrays?

A) We would just make the inner array hold three strings, perhaps like this:

String[][] countriesCitiesAndPresidents;
//now allocate like this
countriesAndCities = new String[5][3];
//and initialize like this
countriesCitiesAndPresidents [0][0] = "United Kingdom";
countriesCitiesAndPresidents [0][1] = "London";
countriesCitiesAndPresidents [0][3] = "Cameron";//at time of writing

Q2) In our persistence example, we saved a continually updating string to a file so that it persisted after the app had been shut down and restarted. This is like asking the user to click on a Save button. Summoning all your knowledge of Chapter 2, Getting Started with Android, can you think of a way to save the string without saving it by the button click but just when the user quits the app?

A) Override the onPause life cycle method and put the code to save the string in there, like this:

@Override
    protected void onPause() {
        editor.putString(stringName, currentString);
        editor.commit();
    }

Q3) Other than increasing the difficulty level, how could we make the memory game harder?

A) We could simply alter the pause in our thread execution to mention a lower number, giving the player less thinking time, like this:

myHandler.sendEmptyMessageDelayed(0, 450);
//This halves the players thinking time

Q4) Using the plain Android UI with the dull grey buttons isn't very exciting. Take a look at the UI elements in the visual designer. Can you work out how to use an image for our button background?

A) Simply add some .png graphics to the drawable-mdpi folder and then find the background property in the Properties window while your button is selected. Click to edit the property in the usual way and choose the graphic you added to the drawable-mdpi folder.