⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 auctionwatch.java

📁 Auction class for mobile development
💻 JAVA
字号:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.rms.*;

public class AuctionWatch extends MIDlet implements CommandListener {
  private Command exitCommand, addCommand, deleteCommand, backCommand,
    saveCommand;
  private Display display;
  private List mainScreen;
  private Form itemScreen;
  private TextField numberField, descriptionField;
  private ItemDB db = null;
  private Vector itemIDs = new Vector();

  public AuctionWatch() {
    // Get the Display object for the MIDlet
    display = Display.getDisplay(this);

    // Create the commands
    exitCommand = new Command("Exit", Command.EXIT, 2);
    addCommand = new Command("Add", Command.SCREEN, 3);
    deleteCommand = new Command("Delete", Command.SCREEN, 3);
    backCommand = new Command("Back", Command.BACK, 2);
    saveCommand = new Command("Save", Command.OK, 3);

    // Create the main screen
    mainScreen = new List("Items", List.IMPLICIT);

    // Set the Exit and Add commands for the main screen
    mainScreen.addCommand(exitCommand);
    mainScreen.addCommand(addCommand);
    mainScreen.addCommand(deleteCommand);
    mainScreen.setCommandListener(this);

    // Create the item screen
    itemScreen = new Form("Item Info");
    numberField = new TextField("Item #", "", 12, TextField.NUMERIC);
    itemScreen.append(numberField);
    descriptionField = new TextField("Description", "", 30, TextField.ANY);
    itemScreen.append(descriptionField);

    // Set the Back and Save commands for the item screen
    itemScreen.addCommand(backCommand);
    itemScreen.addCommand(saveCommand);
    itemScreen.setCommandListener(this);

    // Open the item database
    try {
      db = new ItemDB("items");
    }
    catch(Exception e) {
      System.err.println("EXCEPTION: Problem opening the database.");
    }

    // Read through the database and build a list of record IDs
    RecordEnumeration records = null;
    try {
      records = db.enumerateItemRecords();
      while(records.hasNextElement())
        itemIDs.addElement(new Integer(records.nextRecordId()));
    }
    catch(Exception e) {
      System.err.println("EXCEPTION: Problem reading the item records.");
    }

    // Read through the database and fill the item list
    records.reset();
    try {
      while(records.hasNextElement()) {
        Item item = new Item(records.nextRecord());
        mainScreen.append(item.getDescription(), null);
      }
    }
    catch(Exception e) {
      System.err.println("EXCEPTION: Problem reading the item records.");
    }
  }

  public void startApp() throws MIDletStateChangeException {
    // Set the current display to the main screen
    display.setCurrent(mainScreen);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
    // Close the item database
    try {
      db.close();
    }
    catch(Exception e) {
      System.err.println("EXCEPTION: Problem closing the database.");
    }
  }

  public void commandAction(Command c, Displayable s) {
    if (c == exitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }
    else if (c == addCommand) {
      // Clear the item fields
      numberField.setString("");
      descriptionField.setString("");

      // Set the current display to the item screen
      display.setCurrent(itemScreen);
    }
    else if (c == deleteCommand) {
      // Get the record ID of the currently selected item
      int index = mainScreen.getSelectedIndex();
      int id = ((Integer)itemIDs.elementAt(index)).intValue();

      // Delete the item record
      db.deleteItemRecord(id);
      itemIDs.removeElementAt(index);
      mainScreen.delete(index);
    }
    else if (c == List.SELECT_COMMAND) {
      // Get the record ID of the currently selected item
      int index = mainScreen.getSelectedIndex();
      int id = ((Integer)itemIDs.elementAt(index)).intValue();

      // Retrieve the item record from the database
      Item item = db.getItemRecord(id);

      // Get the live item information
      String liveItemInfo = getLiveItemInfo(item.getNumber());

      // Update the item in the item list with the live info
      mainScreen.set(index, item.getDescription() + "\n" + liveItemInfo, null);
    }
    else if (c == backCommand) {
      // Set the current display back to the main screen
      display.setCurrent(mainScreen);
    }
    else if (c == saveCommand) {
      // Create a record for the item
      int itemNum = 0;
      if (numberField.getString().length() > 0)
        itemNum = Integer.parseInt(numberField.getString());
      Item item = new Item(itemNum, descriptionField.getString());

      // Add the item to the database
      itemIDs.addElement(new Integer(db.addItemRecord(item.pack())));
      mainScreen.append(item.getDescription(), null);

      // Set the current display back to the main screen
      display.setCurrent(mainScreen);
    }
  }

  private String getLiveItemInfo(int inum) {
    StreamConnection conn = null;
    InputStream in = null;
    StringBuffer bidAmount = new StringBuffer(),
      time = new StringBuffer();

    // Build the URL for the Yahoo auction item page
    String url = "http://page.auctions.yahoo.com/auction/" + String.valueOf(inum);

    try {
      // Open the HTTP connection
      conn = (StreamConnection)Connector.open(url);

      // Obtain an input stream for the connection
      in = conn.openInputStream();

      // Read through the page, finding the bid amount and time remaining
      int ch;
      boolean readingBidAmount = false, countingToTime = false,
        readingTime = false, finished = false;
      int timeCountdown = 44;
      while ((ch = in.read()) != -1 && !finished) {
        // Find the first dollar sign
        if (((char)ch) == '$')
          readingBidAmount = true;

        if (readingBidAmount) {
          // Read the bid amount
          if (((char)ch) != '<')
            bidAmount.append((char)ch);
          else {
            readingBidAmount = false;
            countingToTime = true;
          }
        }
        else if (countingToTime) {
          // Skip over to the time remaining
          if (--timeCountdown == 0) {
            countingToTime = false;
            readingTime = true;
          }
        }
        else if (readingTime) {
          // Read the time remaining
          if (((char)ch) != '<')
            time.append((char)ch);
          else
            finished = true;
        }
      }
    }
    catch (IOException e) {
      System.err.println("The connection could not be established.");
    }

    // Remove all "&nbsp;" occurrences from the time string
    int i = 0;
    char c;
    while (i < time.length()) {
      c = time.charAt(i);
      if (c == '&') {
        time.delete(i, i + 6);
        time.insert(i, ' ');
      }
      i++;
    }

    // Display an error message if necessary
    if (bidAmount.length() == 0)
      display.setCurrent(new Alert("Auction Watch",
        "The item is invalid. Please check its item number.", null, AlertType.ERROR));

    return (bidAmount + " " + time);
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -