Saving and loading files from SD card

This is especially useful for saving (and loading) your game's state. It uses SD card by default, but it degrades gracefully to internal memory when the SD card is unavailable. "Why should I save game state to SD card?", you might ask. Well, large part of Android users are using custom ROMs on their devices. They upgrade it often and they often have to wipe the internal memory. Nobody wants to lose progress in any game, so storing it SD card seems better to me. Besides, if you switch phones, it's easy to copy or backup your savegames. Digression aside, let's dive into the code!

 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829
public static boolean saveFile(String fileName, Context context) {
try {
File sdDir = Environment.getExternalStorageDirectory();
String path = sdDir.getAbsolutePath() + "/YOUR_DIR_NAME/";
File sgDir = new File(path);
if (!sgDir.exists()) {
sgDir.mkdirs();
sgDir.createNewFile();
}
FileWriter fw = new FileWriter(path + fileName);
BufferedWriter out = new BufferedWriter(fw);
String toSave = "I want to be saved in a file!";
out.write(toSave);
out.close();
return true;
}
catch (Exception ex) {
try {
FileOutputStream os = context.openFileOutput(fileName, 0);
String toSave = "I want to be saved in a file!";
os.write(toSave.getBytes());
os.flush();
os.close();
return true;
}
catch (Exception ex2) {}
}
return false;
}
This is a function for saving. What's going on here? There are two unobvious things:

  • getExternalStorageDirectory() - returns the root SD card directory (it's a method of android.os.Environment). Use this, instead of hardcoding the /sdcard (or any other) path!
  • context.openFileOutput(fileName, 0) - opens a file associated with this Context's application package (in device's internal memory). More info in the docs.
The rest is just standard Java I/O stuff. Function for loading:
 1 2 3 4 5 6 7 8 91011121314151617181920212223
public static String loadFile(String fileName, Context context) {
try {
File sdDir = Environment.getExternalStorageDirectory();
FileInputStream is = new FileInputStream(sdDir.getAbsolutePath() + "/YOUR_DIR_NAME/" + name);
byte[] byteArray = new byte[is.available()];
is.read(byteArray, 0, byteArray.length);
String content = new String(byteArray);
is.close();
return content;
}
catch (Exception ex) {
try {
FileInputStream is = context.openFileInput(fileName);
byte[] byteArray = new byte[is.available()];
is.read(byteArray, 0, byteArray.length);
String content = new String(byteArray);
is.close();
return content;
}
catch (Exception ex2) {}
}
return null;
}
Nothing new here. Checking whether the given file exists:
 1 2 3 4 5 6 7 8 910111213141516
public static boolean fileExists(String fileName, Context context) {
File sdDir = Environment.getExternalStorageDirectory();
File sg = new File(sdDir.getAbsolutePath() + "/YOUR_DIR_NAME/");
if (sg.exists())
return true;
else
try {
FileInputStream is = context.openFileInput(fileName);
if (is != null)
return true;
}
catch (Exception ex) {
return false;
}
return false;
}

Creating custom, fancy buttons in Android

Ever wondered how to properly create a custom button, which looks different when selected (or clicked) and can be resized? Fortunately it's quite easy in Android. Let's start by creating a bitmap for our button. I'm using Gimp for such things. That's what I got:



(I told you it would be fancy!)
As you can see, I created 4 variants. Accordingly: regular button, pressed button, selected (focused) button and the disabled button. I can create a 4-state button now with such XML:

 1 2 3 4 5 6 7 8 9101112
<?xml version="1.0" encoding="UTF-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
android:drawable="@drawable/button_menu_disabled" />
<item android:state_enabled="true"
android:state_pressed="true" android:drawable="@drawable/button_menu_pressed" />
<item android:state_enabled="true"
android:state_focused="true" android:drawable="@drawable/button_menu_selected" />
<item android:state_enabled="true"
android:drawable="@drawable/button_menu_normal" />
</selector>


Put all the files (button_menu_normal.png, button_menu_pressed.png, button_menu_selected.png, button_menu_disabled.png and the newly created button_menu.xml) in your res/drawable directory. That creates a drawable consisting of our three images, each for one state of the button. If I want to use it in a button, I have to specify my drawable as a button background (in some layout XML file):

 1 2 3 4 5 6 7 8 910
<Button android:id="@+id/new_game"
android:text="New game"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15px"
android:layout_marginRight="15px"
android:layout_marginTop="10px"
android:background="@drawable/button_menu"
/>


Let's run the project! Oh, it doesn't look very nice...



That's because our buttons aren't resizing properly. Android just takes our bitmap and stretches it to fit the button. It's ugly.

Nine-patches, we need you!

Wait, nine-what? Nine-patches (or nine-patch drawables) are the Android's remedy to resizing problem. Basically a nine-patch is an almost-ordinary image, just it's treated by the system differently when resizing. Look at this:



That's a nine-patch image. Two things differ it from a regular image:
  • it has a 1-pixel border with some black pixels
  • it has to be saved with name like my_image.9.png
So what are those black pixels for? They indicate which parts of the image will be stretched. Look:



Android looks at those black pixels and divides the image in 9 parts using them and then resizes the image like that:
  • Parts 1, 3, 7 and 9 aren't resized at all
  • Parts 2 and 8 are resized horizontally
  • Parts 4 and 6 are resized vertically
  • Part 5 is resized horizontally and vertically


So only the pink parts are resized (in one axis) and the most pink part is resized on two axes. (that phrase sounds really weird)

That's how it looks when resized (I left your favourite pink color to show the patches):



Neat! You can create 9-patch images with any image manipulation program, but there's a little tool in the Android SDK for that purpose. Look for it in ANDROID_SDK_DIR/tools/draw9patch.



It's very simple, but it does the job. Play with it for a while or read some instructions here.

Ok, I've changed my button images to nine-patches (so button_menu_normal.png became button_menu_normal.9.png etc.). Let's change the code. The best thing is that we don't have to change anything! If Android sees the button_menu_normal.9.png file, it loads it automatically as a nine-patch image that's available under id @drawable/button_menu_normal. How cool is that?

Running the app gives us nicely resized buttons now.



Summary:
  • create your button image
  • create some variants for clicked, selected and disabled states
  • make 9-patches of it
  • create my_fancy_button.xml file in res/drawable directory
  • set it as your button background in the layout xml file

Easy! I'll continue to dig this subject and add some styling in the next post.

How to stay motivated whilst programming a game

Cliff Harris (known as Cliffski, author of Gratuitous Space Battles) wrote a really nice blog post about motivation in game programming.

Keep a log of what you did each day


That's very important. It just feels good when you can check off some tasks after every coding session. You will notice your progress, even if the changes can't be noticed from inside the game. So, write to-dos for every little thing that needs to be done! I'm using iDeskapp for that. You can read about its "Tasks" feature here.

you need to sell a full-price game direct to a customer every 45 minutes, or you probably won’t make a career as a full-time indie


I would argue with that. Well, maybe not exactly "argue" - I just want to point out that there are a lot of people who aren't full-time indies and don't have to sell a lot of games. Of course, you probably can't make games in your spare time just for fun in the long run, but I think it's how it begins. You have a job and code something in the evenings - for free. Then it just grows naturally to some sort of commercial activity and the next step is a switch to full-time game developer. But you don't have to sell zillions of copies of your first game.

Anyway, Cliffski's got some really good advices there and I encourage you to read it.

Another post on sales

Did I say something about lack of promos on Android Market? Well, here you go: Glu just started a sale, the following games are available for just 0.99$ each until July 6th.

- Build-A-Lot
- Call of Duty: Modern Warfare 2
- Diner Dash 2
- Family Guy Uncensored
- Stranded: Mysteries of Time
- Super KO Boxing 2
- Tony Hawk VERT
- World Series of Poker - Hold 'Em Legend



Have fun!

Powered by Blogger