Quotes MIDlet : Ticker « J2ME « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Collections Data Structure
8. Database SQL JDBC
9. Design Pattern
10. Development Class
11. Email
12. Event
13. File Input Output
14. Game
15. Hibernate
16. J2EE
17. J2ME
18. JDK 6
19. JSP
20. JSTL
21. Language Basics
22. Network Protocol
23. PDF RTF
24. Regular Expressions
25. Security
26. Servlets
27. Spring
28. Swing Components
29. Swing JFC
30. SWT JFace Eclipse
31. Threads
32. Tiny Application
33. Velocity
34. Web Services SOA
35. XML
Microsoft Office Word 2007 Tutorial
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
PHP
Python
SQL Server / T-SQL
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Java » J2ME » TickerScreenshots 
Quotes MIDlet
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.com/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.com and 
   // retrieve the data for a given 
   // stock symbol.
   public String getQuote(String inputthrows 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);
   }
}


           
       
Related examples in the same category
1. Shared TickerShared Ticker
2. TickerListTickerList
3. Stock WatcherStock Watcher
w__w___w.___ja___v___a2___s_.__c__o_m__ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.