Home arrow Java arrow Page 8 - Storing and Retrieving Data
JAVA

Storing and Retrieving Data


Storing bytes of data locally on a device equipped for the Mobile Internet Device Profile (MIDP) is easy. MIDP allows you to store arrays of bytes. But what if the data you need to store isn't in the form of bytes? And how can you make the data small enough so that storing it on a device with a relatively small amount of memory is not a problem? That's where this article comes in. It is excerpted from the book J2ME Games with MIDP2, written by Carol Hamer (Apress, 2004; ISBN: 1590593820).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 24
May 12, 2005
TABLE OF CONTENTS:
  1. · Storing and Retrieving Data
  2. · Serializing More Complex Data Using Streams
  3. · Using Data Types and Byte Arithmetic
  4. · Applying Data Storage to a Game
  5. · Converting an array of bytes into a dungeon
  6. · Creating the Complete Example Game
  7. · DungeonManager.java
  8. · Doors and keys

print this article
SEARCH DEVARTICLES

Storing and Retrieving Data - Doors and keys
(Page 8 of 8 )

The princess and the crown Sprites were too simple to warrant making whole subclasses for them (similarly I didnít bother to subclass TiledLayer for the background this time). But for the doors and keys, I wanted to store their colors in the Sprite object itself, so I created a subclass, DoorKey.java (see Listing 5-10).

Listing 5-10. DoorKey.java

  package net.frog_parrot.dungeon;
 
import javax.microedition.lcdui.*;
  import javax.microedition.lcdui.game.*;
 
/**
   
* This class represents doors and keys.
    *
   
* @author Carol Hamer
   
*/
  public class DoorKey extends Sprite {
 
//-------------------------------------------------------   // fields
 
/**
   
* The image file shared by all doors and keys.
   
*/
  public static Image myImage;
 
/**
   
* A code int that indicates the door or key's color.
   
*/
  private int myColor;
 
//-------------------------------------------------------  // get/set data
 
/**
   
* @return the door or key's color.
    */
  public int getColor() {
   
return(myColor);
  }
 
//-------------------------------------------------------  // constructor and initializer
  static {
    try {
      myImage = Image.createImage("/images/keys.png");
    } catch(Exception e) {
      throw(new RuntimeException(
          "DoorKey.-->failed to load image, caught "
          + e.getClass() + ": " + e.getMessage()));
    }
  }
 
/**
   
* Standard constructor sets the image to the correct frame
   
* (according to whether this is a door or a key and what
   
* color it should be) and then puts it in the correct location.
    */
 
public DoorKey(int color, boolean isKey, int[] gridCoordinates) {
    super(myImage, DungeonManager.SQUARE_WIDTH, DungeonManager.SQUARE_WIDTH);
    myColor = color;
    int imageIndex = color * 2;
    if(isKey) {
     
imageIndex++;
    }
    setFrame(imageIndex);
    setPosition(gridCoordinates[0] * DungeonManager.SQUARE_WIDTH,
       gridCoordinates[1] * DungeonManager.SQUARE_WIDTH);
  }

}

And, of course, you donít want to forget about the Thread subclass GameThread.java (see Listing 5-11).

Listing 5-11. GameThread.java

  package net.frog_parrot.dungeon;
 
/**
   
* This class contains the loop that keeps the game running.
    *
   
* @author Carol Hamer
   
*/
  public class GameThread extends Thread {
 
//-------------------------------------------------------  // fields
 
/**
   
* Whether the main thread would like this thread
   
* to pause.
   
*/
  private boolean myShouldPause;
 
/**
   
* Whether the main thread would like this thread
   
* to stop.
   
*/
  private static boolean myShouldStop;
 
/**
   
* Ahandle back to the graphical components.
   
*/
  private DungeonCanvas myDungeonCanvas;
  //-------------------------------------------------------  // initialization
 
/**
   
* standard constructor.
    */
  GameThread(DungeonCanvas canvas) {
   
myDungeonCanvas = canvas;
  }
  //-------------------------------------------------------  // actions
 
/**
   
* pause the game.
    */
  void pause() {
   
myShouldPause = true;
  }
 
/**
   
* restart the game after apause.
    */
 
synchronized void resumeGame() {
    myShouldPause = false;
    notify();
  }
  /**
   
* stops the game.
    */
  synchronized void requestStop() {
  myShouldStop = true;
  this.notify();
 
}
 
/**
   
* start the game..
    */
 
public void run() {
    // flush any keystrokes that occurred before the
    // game started:
    myDungeonCanvas.flushKeys();
    myShouldStop = false;
    myShouldPause = false;
    while(true) {
     
if(myShouldStop) {
       
break;
      }
      myDungeonCanvas.checkKeys();
      myDungeonCanvas.updateScreen();
      // you do a very short pause to allow the other thread
      // to update the information about which keys are pressed:
      synchronized(this) {
       
try {
          wait(1);
       
} catch(Exception e) {}
      }
      if(myShouldPause) {
       
synchronized(this) {
          try {
            wait();
          } catch(Exception e) {}
         }
        }
       }
      }

   }

Storing your data locally on the device isnít the only application of transforming your object data into byte arrays (and later converting it back). You can use the same functions that prepare your data to be stored to prepare your data to be transmitted over a network, and you can use the functions that interpret the bytes of data without modification to interpret data that the device receives from a server. In the next chapter, youíll see how to add a little bit of communications code to this same example game to allow a remote server to update the data used by the game.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials