Sort Fields : RecordStore « J2ME « Java Tutorial






Sort Fields
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;

public class SortFieldsMIDlet extends MIDlet implements CommandListener {

  private Command exitCommand = new Command("Exit", Command.EXIT, 1);

  private Display display;

  private String[] names = { "A", "B", "C", "D" };

  private int[] chineseScore = { 74, 98, 89, 76 };

  private int[] englishScore = { 67, 89, 89, 78 };

  private int[] mathScore = { 80, 76, 80, 78 };

  public SortFieldsMIDlet() {
    display = Display.getDisplay(this);
  }

  public void startApp() {
    TextBox aTextBox = new TextBox("Main", null, 256, TextField.ANY);
    RecordStore rs = null;
    boolean existingOrNot = false;

    existingOrNot = existing("aRS3");
    if (existingOrNot) {
      try {
        rs = RecordStore.openRecordStore("aRS3", false);
      } catch (Exception e) {
      }
    } else {
      try {
        rs = RecordStore.openRecordStore("aRS3", true);
      } catch (Exception e) {
      }
    }

    Student aStudent = null;

    try {
      for (int i = 0; i < names.length; i++) {
        aStudent = new Student();
        aStudent.write(names[i], chineseScore[i], englishScore[i], mathScore[i]);
        byte[] data = aStudent.changeToByteArray();
        int recordID = aStudent.getRecordID();
        if (recordID != -1) {
          rs.setRecord(recordID, data, 0, data.length);
        } else {
          recordID = rs.addRecord(data, 0, data.length);
          aStudent.setRecordID(recordID);
        }
        aStudent = null;
      }

      String result = "";
      aStudent = new Student();

      byte[] data;
      int number = 0;
      RecordComparator rc = new sortByAverage();
      RecordEnumeration re = rs.enumerateRecords(null, rc, false);
      while (re.hasNextElement()) {
        int recordID = re.nextRecordId();
        data = rs.getRecord(recordID);
        aStudent.changeFromByteArray(data);
        result += recordID + "\n" + "Name:" + aStudent.getName() + "\n" + ":"
            + aStudent.getChineseScore() + "\n" + ":" + aStudent.getEnglishScore() + "\n" + ":"
            + aStudent.getMathScore() + "\n";
        number++;
      }
      result += "" + number + "\n";
      aTextBox.setString(result);

      aTextBox.setString(result);
      aTextBox.addCommand(exitCommand);
      aTextBox.setCommandListener(this);
      display.setCurrent(aTextBox);
    } catch (Exception e) {
    }
  }
  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public boolean existing(String recordStoreName) {
    boolean existingOrNot = false;
    RecordStore rs = null;
    if (recordStoreName.length() > 32)
      return false;
    try {
      rs = RecordStore.openRecordStore(recordStoreName, false);
    } catch (RecordStoreNotFoundException e) {
      existingOrNot = false;
    } catch (Exception e) {
    } finally {
      try {
        rs.closeRecordStore();
      } catch (Exception e) {
      }
    }
    return existingOrNot;
  }

  public void commandAction(Command c, Displayable s) {
    destroyApp(false);
    notifyDestroyed();
  }
}

class Student {
  private int ID = -1;

  private String name;

  private int chineseScore;

  private int englishScore;

  private int mathScore;

  public void write(String name, int chineseScore, int englishScore, int mathScore) {
    this.name = name;
    this.chineseScore = chineseScore;
    this.englishScore = englishScore;
    this.mathScore = mathScore;
  }

  public void setRecordID(int ID) {
    this.ID = ID;
  }

  public int getRecordID() {
    return ID;
  }

  public byte[] changeToByteArray() {
    byte[] data = null;

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DataOutputStream dos = new DataOutputStream(baos);
      dos.writeUTF(name);
      dos.writeInt(chineseScore);
      dos.writeInt(englishScore);
      dos.writeInt(mathScore);
      data = baos.toByteArray();

      baos.close();
      dos.close();
    } catch (Exception e) {
    }
    return data;
  }

  public void changeFromByteArray(byte[] data) {
    try {
      ByteArrayInputStream bais = new ByteArrayInputStream(data);
      DataInputStream dis = new DataInputStream(bais);

      name = dis.readUTF();
      chineseScore = dis.readInt();
      englishScore = dis.readInt();
      mathScore = dis.readInt();

      bais.close();
      dis.close();
    } catch (Exception e) {
    }
  }

  public String getName() {
    return name;
  }

  public int getChineseScore() {
    return chineseScore;
  }

  public int getEnglishScore() {
    return englishScore;
  }

  public int getMathScore() {
    return mathScore;
  }
}

class sortByAverage implements RecordComparator {
  public int compare(byte[] rec1, byte[] rec2) {
    DataInputStream student1 = new DataInputStream(new ByteArrayInputStream(rec1));
    DataInputStream student2 = new DataInputStream(new ByteArrayInputStream(rec2));
    int average1 = 0;
    int average2 = 0;
    try {
      average1 = (student1.readInt() + student1.readInt() + student1.readInt()) / 3;
      average2 = (student2.readInt() + student2.readInt() + student2.readInt()) / 3;

    } catch (Exception e) {
    }

    if (average1 == average2)
      return RecordComparator.EQUIVALENT;
    else if (average1 < average2)
      return RecordComparator.FOLLOWS;
    else
      return RecordComparator.PRECEDES;

  }
}








31.47.RecordStore
31.47.1.Load yahoo stock quote
31.47.2.Add records to RecordStore
31.47.3.delete RecordStore
31.47.4.Filter FieldsFilter Fields
31.47.5.Get record from RecordStoreGet record from RecordStore
31.47.6.Save data to RecordStoreSave data to RecordStore
31.47.7.Record MonitorRecord Monitor
31.47.8.Retrieve AllRetrieve All
31.47.9.Sort FieldsSort Fields
31.47.10.Record Enumeration
31.47.11.RecordStore read and write
31.47.12.Read and write mixed data types with RecordStore
31.47.13.Mixed Record Enumeration
31.47.14.Sort records in RecordStore
31.47.15.Sort Mixed Record DataType
31.47.16.Search record in RecordStore
31.47.17.Search Mixed Record Data Type