Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Revision as of 06:49, 4 June 2009 by tanjaluodes (Talk | contribs)

How to create a high score database in Java ME

From Wiki
Jump to: navigation, search

Every game should have a high score system to allow gamers to challenge other gamers or themselves.

Java ME use Record Management System (RMS) to allows developers to save and restore data over different application sessions. So, for creating a quick high-score system saving name of the user and points, you can use the following code.


Source code

Adding a new high-score

// We open the recordstore
RecordStore highscore = RecordStore.openRecordStore("High Score", true);
// To add a new HiScore we use a quick string comma-separated
String str = new String("John,3400");
byte [] strb = str.getBytes();
int id = highscore.addRecord(strb, 0, strb.length);

Retrieving top high-scores

RecordStore highscore = RecordStore.openRecordStore("High Score", true);
// To read all hiscores saved on the RMS
RecordEnumeration enum = highscore.enumerateRecords(null, null, false);
int id;
byte[] record;
String str;
while (enum.hasNextElement( )) {
id = enum.nextRecordId( );
record = highscore.getRecord(id);
str = new String(record);
// Operate with str to extract name and points

How to retrieve correctly sorted scores

To sort the scores from the highest to the lowest one, an option is to implement the RecordComparator interface, and to use it when calling the RecordStore enumerateRecords() method.

A basic implementation of a RecordComparator that sorts the scores stored is the following one:

class ScoresComparator implements RecordComparator
public int compare(byte[] arg0, byte[] arg1)
int score0 = 0, score1 = 0;
for(int i = 0; i < arg0.length; i++)
if(arg0[i] == ',')
score0 = Integer.parseInt(new String(arg0, i + 1, arg0.length - i - 1));
for(int i = 0; i < arg1.length; i++)
if(arg1[i] == ',')
score1 = Integer.parseInt(new String(arg1, i + 1, arg1.length - i - 1));
if(score0 < score1)
return 1;
else if(score0 == score1)
return 0;
return -1;

So, the previous call to enumerateRecords() will accordingly change:

RecordEnumeration enumerator = highscore.enumerateRecords(null, new ScoresComparator(), false);


You can download a sample MIDlet showing the code presented in this article here:

Implementation notes

  • You should use try-catch sentences to catch exceptions on the I/O operation or make a throws.
  • When writing and reading data to and from RMS, you should use separate threads to avoid blocking the MIDlet main thread.

Related resources

103 page views in the last 30 days.