In this demo project, we will put into practice the concepts we learned about it in part 1 and part 2 of the Java tutorials. We will declare and initialize a whole bunch of different types of variable and then we will see the different ways we can use operators on them and the effect it has.
As we are working within the Android environment we will be working with the code that is required by all Android apps and games. We will not explain each and every part of this environment; instead, we will slowly introduce it over the course of the projects. By the end of your first real, playable game you will be very comfortable with the Android system.
This means I will ask you to take a few concepts on faith and accept that the exact under-the-hood goings on of a few of the lines of code we will write will all become clear in later tutorials or projects. So let’s get started.
Create a new Android project and enter GameVariables in the Application Name field and enter VariablesActivity in the Activity Name field. When Android Studio has finished generating the project read on.
Your screen should look something like this.
We need to edit the file which will contain all our Java code. So near the top of the window as indicated in the previous diagram click the VariablesActivity.java tab. You will now be faced with what looks like a rather daunting wall of code.
The good news is we don’t need hardly any of it, so go ahead and delete it all except the line of code at the very top that begins like this.
1 |
package... |
Now what we will do is put in the code which we need to work within. If you read or implemented the previous 3 projects you might remember that all Android games and regular apps as well run in an Activity. An Activity is some code that will be executed when the player taps on the icon representing our game on their device. So we need to put this code in and then do all of our coding within it. Don’t bother typing it, just copy and paste this below the one remaining line of code in your VariablesActivity.java file that starts package.... It is important that you don’t delete the line that starts with package….
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import android.app.Activity; import android.os.Bundle; public class VariablesActivity extends Activity { // This is the entry point to our game @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Our Java code will start here // !!Our code must end here - for now. } } |
The full explanation for this code is unimportant right now and exactly what it does will become clearer over later projects and tutorials but a cursory explanation will be useful- so here it is.
The first two lines we copy & paste that begin with the import keyword, make available some code that was written by the Android development team. More specifically the code that will allow us to wrap up our own Java and make a game.
The next line that starts public class VariablesActivity... is declaring the name of the class which will encompass our entire game. Classes as a topic are deep but do not have to be complicated. If you can accept that our game must be wrapped up in this way then read on. If it kind of makes your head itch then sneak ahead to tutorial number 7: Understanding OOP for coding games in Java, but be sure to come back here again afterward.
The next line of code is where the Android system does its magic and makes life easy for us.
1 |
super.onCreate(savedInstanceState); |
This one line of code sets up our entire game ready for us to do what we want to do. We don’t need to know how it does it although we will learn more about it in later tutorials. Now, at last, we can play with what we learned about variables. Add the code below in between the two comments (repeated below for context).
1 2 3 4 5 6 7 8 9 10 11 |
// Our Java code will start here // Let's declare and initialise a whole bunch of variables in one step int playerScore = 0; String playerName = "Alan Turing"; float valuePi = 3.141f; boolean isAlive = true; // Our next block of code will go here // !!Our code must end here - for now. |
The previous block of code simply declares a bunch of variables and initializes them in one step just as we saw in the Game variables tutorial.
Now we will print out these values. We can use some code already written for us to print out values to the Android console. Here we use the d method contained in the Log class. We then simply add a message and a variable into this method. When you read Organizing our game code with methods then methods will become clearer and when you read Understanding OOP for coding games in Java then classes will become clearer.
For now, let’s just go ahead and use this code to explore our own a little further. Enter the code after the last block of code but before the final comment.
1 2 |
// Our next block of code will go here Log.d("playerScore is", "" + playerScore); |
The first thing you might notice is that the Log keyword is underlined and in red font. This indicates an error. We have this error because we need to add another line of code to import the Log class just like we imported those two other classes. No typing is required here; simply click Log to place the cursor on it and then press the Alt|Enter keyboard combination and a new line of code is added for you after the previous two import... lines of code.
This slightly strange-looking line of code simply prints a message as we will see in a minute. The first pair of quotation marks contain the message "playerScore is ". The next is where we put our variable to work. The empty quotation marks are required even though they cause no output. The + playerScore simply causes the value of playerScore to be output.
Let’s add a load more of these Log.d statements to examine our other variables. Immediately below the previous Log.d... line add these.
1 2 3 |
Log.d("playerName is", "" + playerName); Log.d("valuePi is", "" + valuePi); Log.d("isAlive is", "" + isAlive); |
Now, before we run the code let’s use some operators on our variables to sample what we learned about in the tutorial Changing the value of game variables. Add the following lines of code which change our variables using various operators and then print them out so we can see if all is as expected. Add this code immediately after the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
playerScore ++; // Just incremented player score by 1 playerName = playerName + " was quite good with numbers."; // Yep we can add strings as well // It is called concatenation valuePi = valuePi + 10; // valuePi is now 13.141. valuePi = valuePi + playerScore; // Now valuePi is now 13.141 + 1 isAlive = false; // Uhh, now I'm dead Log.d("playerScore is", "" + playerScore); Log.d("playerName is", "" + playerName); Log.d("valuePi is", "" + valuePi); Log.d("isAlive is", "" + isAlive); |
Now finally, attach an Android device and deploy/run the game. Note that although the output to the actual device is the same static display as our blank game project, it is the output in the Logcat window on the Android tab that we are interested in. This window, pictured below should appear automatically. You will probably need to click on the image below to expand it in order to read the highlighted output.
In the Logcat window, we can see that our variables hold the values we initialized them to and that the operators had the expected effect. We will use this technique of outputting to the Android Logcat console to help us debug our game projects.
Here is the entire code laid out with all the indentations. Note that the package... line at the top might be different from your code depending on how you built your project. It is important that this line of code remains the same way that Android Studio created it for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import android.app.Activity; import android.os.Bundle; import android.util.Log; public class VariablesActivity extends Activity { // This is the entry point to our game @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Our Java code will start here // Let's declare and initialise a whole bunch of variables in one step int playerScore = 0; String playerName = "Alan Turing"; float valuePi = 3.141f; boolean isAlive = true; // Our next block of code will go here Log.d("playerScore is", "" + playerScore); Log.d("playerName is", "" + playerName); Log.d("valuePi is", "" + valuePi); Log.d("isAlive is", "" + isAlive); playerScore ++; // Just incremented player score by 1 playerName = playerName + " was quite good with numbers."; // Yep we can add strings as well // It is called concatenation valuePi = valuePi + 10; // valuePi is now 13.141 valuePi = valuePi + playerScore; // Now valuePi is now 13.141 + 1 isAlive = false; // Uhh, now I'm dead Log.d("playerScore is", "" + playerScore); Log.d("playerName is", "" + playerName); Log.d("valuePi is", "" + valuePi); Log.d("isAlive is", "" + isAlive); // !!Our code must end here - for now } } |
The logical next step would be to read the tutorial about checking for conditions in our game.
Hi mate! First of all i just want to thank you for this amazing course , i was looking for a fresh and easy-to-use website that would get me started in game developing and so far this has been the best (by far), i really dig the way your organize and present the information , however , i encountered a problem when i started Android Studio, it said gradle project sync completed with some errors. Can you help me with this?
Hi Francisco,
Many thanks for your comment, it could be a couple of things.
Did the error occur immediately after you built the project? If so this could be a bug with Android Studio. Just try clicking between the text and design tab this gets around this weird intermittent bug.
If the error occurred after you have added code then the answer probably lies in the window at the bottom of Android Studio where you should be able to expand your error message to get the specific error details. These details might solve your problem for you or you could post them here or in a Google search.
Good luck Francisco, let me know if you need more help and I will do my best.
Thanks!
Hi,
I really enjoy reading through this site. I have a little experience with Java due to an online course and playing around with eclipse. I do have an issue using Android studio and I am not sure what is causing the problem. None of my devices seem to show up when connected. ADB is activated but I can only select the emulator. My android versions might be the problem with version 2.3.4 & 4.1.1.
Hi Ronald,
It is possible you need to install a driver for your device, especially the 2.3.4 device. Also check that you have USB debugging enabled on the device. If your devices are recognized by windows when you plug them in via USB the problem is most likely the latter one. If they are not then then try searching for the device manufacturers drivers on Google.
Thanks for your comment.
Hi There,
I have been using various software and tutorials online and so far, this is by far the most useful and interesting. Especially the compiler used seems vry strong and robust. In the beginning I had some issues where my own android devices did not have the proper android version (which was resolved quite easily), but now I started using this course at work as well and I instantly run into some security issues.
I cannot run ANY code to either emulator or real device due to Intel HAXM requirement to run this AVD (this needs to be set in the security settings of my BIOS). Naturally my company will not grant me access to change this.
I wonder if there is a way to run the code and get the corresponding output on my local screen without attaching an android device (like it works on Eclipse and other compilers)?
This might not be solvable. Try exporting the actual apk and then using dropbox (or similar) to add it to the device. It is likely they would have security to prevent this too. But worth a try.
Thanks for the info John, affraid this won’t work either. I’m trying to look for an online compiler where I can import the library.
Where is this information stored:
package com.gamecodeschool.gamevariables2;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
Is it in the Android Studios itself??
Can you export the APK to the PC? Can you install chrome browser? If yes to both of these try ARK welder to run apps in chrome browser. Here is a tutorial to install Ark welder http://www.howtogeek.com/214734/how-to-use-googles-arc-welder-to-run-android-apps-in-chrome/
Hello. This is a great introductory course by the way. I’m very new to programming and learning code. I copy and pasted the block of code at the end, but when I ran the program, I only get a blank game. Any Ideas? Thanks in advance.
Nevermind it’s supposed to be blank. Whoops. Thanks Anyways.
Hi David,
Thanks for your comments. Yes, all the code in the Tutorials section is just for learning purposes and all the code in the Projects section actually does something.
I have a problem .
I get an error that is saying that is a problem with this line :
super.onCreate(savedInstanceState);
Exactly the bug is saying this : savedInstanceState doesn’t exist but I have did this like you .
Hi George,
My best guess is that there is another problem in the code that is making this line appear as an error. savedInstanceState is declared/created in the line that comes before it so it must exist. The problem is likely a syntax problem. Have you tried to copy and paste the listing from the end of the tutorial? Remember to not overwrite your auto-generated package declaration (the first line of code that starts package...)while copy and pasting and not to use my package.... Hope this helps.
package com.gamecodeschool.gamevariables;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class VariablesActivity extends Activity {
//This is the entry code for our game
@Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(savedInstanceState);
// Our java code will start here
//Let’s declare and initialize a whole bunch of new variables in one step
int playerScore = 0;
String playerName = “Alan Turing”;
float valuePi = 3.141f;
boolean isAlive = true;
// Our next block of code will go right here
Log.d(“playerScore is”, “” + playerScore);
Log.d(“playerName is”, “” + playerName);
Log.d(“valuePi is”, “” + valuePi);
Log.d(“isAlive is”, “” + isAlive);
playerScore++;
// Just increment the player score by 1
playerName = playerName + “was quite good with numbers”;
// Yep , we can add strings as well
// It’s called concatenation
valuePi = valuePi + 10;
// Now valuePi is now 13.141
valuePi = valuePi + playerScore;
// Now valuePi is now 13.141 + 1
isAlive = false;
// Uh , i’m dead
Log.d(“playerScore is”, “” + playerScore);
Log.d(“playerName is”, “” + playerName);
Log.d(“valuePi is”, “” + valuePi);
Log.d(“isAlive is”, “” + isAlive);
//Our game code must end here – for now
}
}
That was my entire code . Can you help me?
Is this package com.gamecodeschool.gamevariables; the actual package name you used when you created the project? If not then this is likely the cause.
Yes , the package is correct . What should I do?
Im a bit baffled so I just tried it myself and it seemed OK. I can only think the project type might not be right or some other file is causing the error. Try starting a new project, use the Empty Activity template. Copy, paste and overwrite the entire code except the package… line, cross your fingers and hit the play button.
I have did this . It doesn’t help. Any other help ?
I have been staring at this for ages and I just realized there is a d missing on the end of the word save in the line protected void onCreate(Bundle saveInstanceState) { in the code you posted. But it seems to be there in the code in the tutorial so I don’t know how the copy & paste failed. The line should be protected void onCreate(Bundle savedInstanceState) {. Also, when I posted your code into Android Studio it didn’t like the quote marks ” but that could just be the formatting of the comments.
Sorry for the time you losed , i have really laughed at your last comment. Anyway , you make some cool tuts so i wanna thank you. When you will do the c++ game programming course?
Here are some getting started C++ tutorials and some projects using C++ and SFML. And the course/learning pathway will be published here in a few weeks.
One observation:
if I use a Log expression such as Log.d(“Some message”,”Some more message”); , the log message is visible in the Logcat. However, if I use a statement like
Log.d(“Some message”,””); It does not show up on Logcat at all. Notice that there is no character between the quotes in the second argument of the method log.d in the above statement. I wonder why? Any comments on this John?
Also there seems to be a limit on the number of characters that can be printed inside the Log message(I think its only 26 characters). Its weird to have such a constraint.
Yes, there are limits. I guess for technical reasons behind the scenes in Android Studio because a String maximum length is huge. You can chain together multiple Log.d calls if you need to build up a longer message. Regarding the message not printing with an empty String, I think that the method checks for this and rejects the entire call when it occurs.
I Hope this helps a bit.