Java/J2ME/Ticker — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 06:37, 1 июня 2010

Quotes MIDlet

/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import java.util.Enumeration;
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
public class QuotesMIDlet extends MIDlet implements CommandListener {
   Display display = null;
   List menu = null; // main menu
   List choose = null;
   TextBox input = null;
   Ticker ticker = new Ticker("Database Application");
   String quoteServer = 
   "http://quote.yahoo.ru/d/quotes.csv?s=";
   String quoteFormat = "&f=slc1wop"; // The only quote format supported
   static final Command backCommand = new Command("Back", Command.BACK, 0);
   static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
   static final Command saveCommand = new Command("Save", Command.OK, 2);
   static final Command exitCommand = new Command("Exit", Command.STOP, 3);
   String currentMenu = null;
   // Stock data
   String name, date, price;
    
   // record store
   StockDB db = null;
   public QuotesMIDlet() { // constructor
   }
   // start the MIDlet
   public void startApp() throws MIDletStateChangeException {
      display = Display.getDisplay(this);
      // open a db stock file
      try {
         db = new StockDB("mystocks");
      } catch(Exception e) {}
         menu = new List("Stocks Database", Choice.IMPLICIT);
         menu.append("List Stocks", null);
         menu.append("Add A New Stock", null);
         menu.addCommand(exitCommand);
         menu.setCommandListener(this);
         menu.setTicker(ticker);
         mainMenu();
   }
   public void pauseApp() {
      display = null;
      choose = null;
      menu = null;
      ticker = null;
       
      try {
         db.close();
         db = null;
      } catch(Exception e) {}
   }
   public void destroyApp(boolean unconditional) {
      try {
         db.close();
      } catch(Exception e) {}
      notifyDestroyed();
   }
   void mainMenu() {
      display.setCurrent(menu);
      currentMenu = "Main"; 
   }
   // Construct a running ticker 
   // with stock names and prices
   public String tickerString() {
      StringBuffer ticks = null;
      try {
         RecordEnumeration e = db.enumerate();
         ticks = new StringBuffer();
         while(e.hasNextElement()) {
            String stock1 = new String(e.nextRecord());
            ticks.append(Stock.getName(stock1));
            ticks.append(" @ ");
            ticks.append(Stock.getPrice(stock1));
            ticks.append("    ");
         }
      } catch(Exception ex) {}
         return (ticks.toString());
   }
   // Add a new stock to the record store 
   // by calling StockDB.addNewStock()
   public void addStock() {
      input = new TextBox("Enter a Stock Name:", "", 5, TextField.ANY);
      input.setTicker(ticker);
      input.addCommand(saveCommand);
      input.addCommand(backCommand);
      input.setCommandListener(this);
      input.setString("");
      display.setCurrent(input);
      currentMenu = "Add";
   }
   // Connect to quote.yahoo.ru and 
   // retrieve the data for a given 
   // stock symbol.
   public String getQuote(String input) throws IOException, NumberFormatException {
      String url = quoteServer + input + quoteFormat;
      StreamConnection c = (StreamConnection)Connector.open(
                            url, Connector.READ_WRITE);
      InputStream is = c.openInputStream();
      StringBuffer sb = new StringBuffer();
      int ch;
      while((ch = is.read()) != -1) {
        sb.append((char)ch);
      }
      return(sb.toString());
   }
   
   // List the stocks in the record store
   public void listStocks() {
      choose = new List("Choose Stocks", Choice.MULTIPLE);
      choose.setTicker(new Ticker(tickerString()));
      choose.addCommand(backCommand);
      choose.setCommandListener(this);
      try {
         RecordEnumeration re = db.enumerate();
         while(re.hasNextElement()) {
            String theStock = new String(re.nextRecord());
            choose.append(Stock.getName(theStock)+" @ " +
                          Stock.getPrice(theStock),null);
         }
      } catch(Exception ex) {}
      display.setCurrent(choose);
      currentMenu = "List"; 
   }
 
   // Handle command events 
   public void commandAction(Command c, Displayable d) {
      String label = c.getLabel();
      if (label.equals("Exit")) {
         destroyApp(true);
      } else if (label.equals("Save")) {
         if(currentMenu.equals("Add")) {
            // add it to database
            try {
               String userInput = input.getString();
              String pr = getQuote(userInput);
              db.addNewStock(pr);
              ticker.setString(tickerString()); 
            } catch(IOException e) {
            } catch(NumberFormatException se) {
            }
            mainMenu();
          } 
      } else if (label.equals("Back")) {
         if(currentMenu.equals("List")) {
            // go back to menu
            mainMenu();
         } else if(currentMenu.equals("Add")) {
            // go back to menu
            mainMenu();
         }
      } else {
         List down = (List)display.getCurrent();
         switch(down.getSelectedIndex()) {
            case 0: listStocks();break;
            case 1: addStock();break;
         }
      }
   }
}

class StockDB {
   RecordStore recordStore = null;
   public StockDB() {}
   // Open a record store with the given name
   public StockDB(String fileName) {
      try {
         recordStore = RecordStore.openRecordStore(fileName, true);
      } catch(RecordStoreException rse) {
         rse.printStackTrace();
      }
   }
   // Close the record store
   public void close() throws RecordStoreNotOpenException,RecordStoreException {
      if (recordStore.getNumRecords() == 0) {
         String fileName = recordStore.getName();
         recordStore.closeRecordStore();
         recordStore.deleteRecordStore(fileName);
      } else {
         recordStore.closeRecordStore();
      }
   }
   // Add a new record (stock) 
   // to the record store
   public synchronized void addNewStock(String record) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DataOutputStream outputStream = new DataOutputStream(baos);
      try {
         outputStream.writeUTF(record);
      } catch (IOException ioe) {
         System.out.println(ioe);
         ioe.printStackTrace();
      }
      byte[] b = baos.toByteArray();
      try {
         recordStore.addRecord(b, 0, b.length);
      } catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
      }
   }
   // Enumerate through the records.
   public synchronized RecordEnumeration enumerate() throws
                       RecordStoreNotOpenException {
      return recordStore.enumerateRecords(null, null, false);
   }
}
class Stock {
   private static String name, time, price;
   // Given a quote from the server, 
   // retrieve the name, 
   //price, and date of the stock
   public static void parse(String data) {
      int index = data.indexOf("""); 
      name = data.substring(++index,(index = data.indexOf(""", index)));
      index +=3;
      time = data.substring(index, (index = data.indexOf("-", index))-1);
      index +=5;
      price = data.substring(index, (index = data.indexOf("<", index)));
   }
   // Get the name of the stock from 
   // the record store
   public static String getName(String record) {
      parse(record);
      return(name);
   }
  
   // Get the price of the stock from 
   // the record store
   public static String getPrice(String record) {
      parse(record);
      return(price);
   }
}





Shared Ticker

/*--------------------------------------------------
* SharedTicker.java
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SharedTicker extends MIDlet implements CommandListener
{
  private Display display;    // Reference to Display object
  private List lsProducts;   // Main productlist
  private Alert alHelp;      // Alert to show text and image
  private Ticker tkSale;     // Ticker of what"s on sale
  private Command cmExit;    // Command to exit the MIDlet
 
  public SharedTicker()
  {
    display = Display.getDisplay(this);
    
    cmExit = new Command("Exit", Command.SCREEN, 1);
    tkSale = new Ticker("Current Sale: Torchiere Lamp only $29.00");
    lsProducts = new List("Products", Choice.IMPLICIT);
    lsProducts.append("Floor Lamp", null);
    lsProducts.append("Chandelier", null);
    lsProducts.append("Help", null);    
    lsProducts.addCommand(cmExit);
    lsProducts.setCommandListener(this);
    lsProducts.setTicker(tkSale);
  }
  public void startApp()
  {
    display.setCurrent(lsProducts);
  }
  public void pauseApp()
  { 
  }
  public void destroyApp(boolean unconditional)
  {
  }
  public void showAlert()
  {
    try
    { 
      // Create an image
      Image im = Image.createImage("/help.png");
      // Create Alert, add text and image, no sound
      alHelp = new Alert("Help Information", 
                          "Over 300 unique lighting products!", 
                          im, null);
      alHelp.setTimeout(Alert.FOREVER);                          
      alHelp.setTicker(tkSale);
    }    
    catch(Exception e)
    {
      System.out.println("Unable to read png image.");
    }
    
    // Display the Alert. Once dismissed, return to product list
    display.setCurrent(alHelp, lsProducts);      
  }
  public void commandAction(Command c, Displayable s)
  {
    
    if (c == List.SELECT_COMMAND)
    {
      switch (lsProducts.getSelectedIndex())
      {
        case 0:
          System.out.println("Floor Lamp selected");            
          break;
  
        case 1:
          System.out.println("Chandelier selected");            
          break;
          
        case 2:
          showAlert();
          break;
      }
    }
    else if (c == cmExit)
    {
      destroyApp(true);
      notifyDestroyed();
    }
  }
}





Stock Watcher

/* License
 * 
 * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  
 *  * Redistribution of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 * 
 *  * Redistribution in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *  
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility. 
 */
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public class StockWatcher extends MIDlet {
  Display      display;
  Ticker       ticker = new Ticker( "" );
  Command      exitCommand = new Command( 
                                             "Exit", Command.EXIT, 1 );
  Timer        timer = new Timer();
  StockChecker checker = new StockChecker();
  TickerForm   form = new TickerForm();
  Alert        alert = new Alert( "Stock Alert!" );
  public StockWatcher() {
    display = Display.getDisplay( this );
    alert.setTimeout( Alert.FOREVER );
  }
  protected void destroyApp( boolean unconditional ) { }
  protected void startApp() {
    display.setCurrent( form );
    timer.schedule( checker, 0, 30000 );
  }
  protected void pauseApp() { }
  public void exit(){
    timer.cancel();
    destroyApp( true );
    notifyDestroyed();
  }
  // Display a simple form to hold the ticker
  class TickerForm extends Form implements CommandListener {
    public TickerForm(){
      super( "Stock Watch" );
      setTicker( ticker );
      addCommand( exitCommand );
      setCommandListener( this );
    }
    public void commandAction( Command c, Displayable d ){
      exit();
    }
 }
                    
 // Check the stock values and put up an alert if
 // they"re beyond certain limits....
 class StockChecker extends TimerTask {
   Random       generator = new Random();
   int          sybsValue = 20000;
   int          sunwValue = 30000;
   int          ibmValue = 40000;
   StringBuffer buf = new StringBuffer();
   public void run(){
     String values = getStockValues();
     ticker.setString( values );
     if( sybsValue < 18000 || sybsValue > 22000 ||
          sunwValue < 28000 || sunwValue > 32000 ||
          ibmValue < 38000 || ibmValue > 42000 ){
       alert.setString( values );
     }
     if( !alert.isShown() ){
       display.setCurrent( alert, form );
     }
   }
   private String getStockValues(){
     sybsValue = randomStockValue( sybsValue );
     sunwValue = randomStockValue( sunwValue );
     ibmValue = randomStockValue( ibmValue );
     buf.setLength( 0 );
     appendValue( "SYBS", sybsValue );
     appendValue( "SUNW", sunwValue );
     appendValue( "IBM", ibmValue );
     return buf.toString();
   }
   // Generate a random stock value... in the
   // real world you"d use HTTP to obtain the
   // stock value from a broker"s website.
   private int randomStockValue( int oldVal ){
     int incr1 = ( generator.nextInt() % 2 );
     int incr2 = ( generator.nextInt() % 16 );
     if( incr1 < 1 ){
       oldVal -= incr1 * 1000;
     } else {
       oldVal += ( incr1 - 2 ) * 1000;
     }
     if( incr2 < 8 ){
       oldVal -= incr2 * 250;
     } else {
       oldVal += incr2 * 250;
     }
     return oldVal;
   }
   private void appendValue( String stock, int val ){
     buf.append( stock );
     buf.append( " " );
     buf.append( Integer.toString( val / 1000 ) );
     buf.append( "." );
     buf.append( Integer.toString( val % 1000 ) );
     buf.append( " " );
   }
 }
}





TickerList

/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: TickerList
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: TickerList.jar
MIDlet-1: TickerList, , TickerList
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TickerList extends MIDlet implements CommandListener
{
  private Display display; 
  private List list; 
  private final String tech;
  private final String entertain;
  private Ticker ticker; 
  private Command exit; 
  private Command submit;
  public TickerList()
  {
    display = Display.getDisplay(this);
    tech = new String ("IBM 55 MSFT 32 SUN 52 CISCO 87");
    entertain = new String ("CBS 75 ABC 455 NBC 243 GE 21");
    exit = new Command("Exit", Command.SCREEN, 1);
    submit = new Command("Submit", Command.SCREEN, 1);
    ticker = new Ticker(tech); 
    list = new List("Stock Ticker", Choice.EXCLUSIVE);
    list.append("Technology", null);
    list.append("Entertainment", null);
    list.addCommand(exit);
    list.addCommand(submit);
    list.setCommandListener(this);
    list.setTicker(ticker);
  }
  public void startApp()
  {
    display.setCurrent(list);
  }
  public void pauseApp()
  { 
  }
  public void destroyApp(boolean unconditional)
  {
  }
  public void commandAction(Command command, Displayable display)
  {
    if (command == exit)
    {
      destroyApp(true);
      notifyDestroyed();
    }
    else if (command == submit)
    {
      if (list.getSelectedIndex() == 0)
      {
         ticker.setString (tech);
      }
      else
      {
        ticker.setString(entertain);
      }
    }
  }
}