📄 stockmidlet.java
字号:
try { RecordStore settings = RecordStore.openRecordStore("Settings", true); refresh_interval = Integer.valueOf(new String(settings.getRecord(1))) .intValue(); settings.closeRecordStore(); // No settings file existed } catch (Exception e) { refresh_interval = 900000; } } // synchronized firstTime = true; } /** * <p>This method is invoked when the <code>MIDlet</code> * is ready to run and * starts/resumes execution after being in the <code>Paused</code> * state. The * <code>MIDlet</code> acquires any resources it needs, * enters the * <code>Active</code> state and begins to perform its service, * which in this * case means it displays the main menu on the screen.</p> * * <p>The method proceeds like so:</p> * <li> open the <code>StockDatabase</code> and the * <code>AlertDatabase</code></li> * <li> read the settings data from the settings * <code>RecordStore</code></li> * <li> create the string to be scrolled across the <code>Ticker</code> on * the top of the screens and instantiate the Ticker object using that * string. That string will be constructed of the names and prices of * the stocks in our database</li> * <li> get and store the <code>MIDlet</code>'s * <code>Display</code> object</li> * <li> create and show the main menu</li> * <li> instantiate the <code>TimerTask</code> and <code>Timer</code> and * associate the two setting the refresh interval to the value of * the refresh_interval variable</li> * * @throws <code>MIDletStateChangeException</code> is thrown if the * <code>MIDlet</code> cannot start now but might be able to * start at a later time. * @see javax.microedition.midlet.MIDlet */ public void startApp() { // Make the ticker stockTicker = new Ticker(makeTickerString()); // set the ticker to all forms menu.setTicker(stockTicker); whatif.setTicker(stockTicker); alertList.setTicker(stockTicker); settingsList.setTicker(stockTicker); alertPriceBox.setTicker(stockTicker); updatesForm.setTicker(stockTicker); stockSymbolBox.setTicker(stockTicker); display = Display.getDisplay(this); if (firstTime) { mainMenu(); firstTime = false; } // Set up and start the timer to refresh the stock quotes stockRefreshTask = new StockRefreshTask(); stockRefresh = new Timer(); stockRefresh.schedule(stockRefreshTask, 0, refresh_interval); } /** * <p>This method is invoked by the application management software when * the <code>MIDlet</code> no longer needs to be active. It is a stop * signal for the <code>MIDlet</code> upon which the <code>MIDlet</code> * should release any resources which can be re-acquired through the * <code>startApp<code> method which will be called upon re-activation of * the <code>MIDlet</code>. The <code>MIDlet</code> enters * the <code>Paused</code> * state upon completion of this method.</p> * * @see javax.microedition.midlet.MIDlet */ public void pauseApp() { synchronized (this) { // free memory used by these objects display = null; stockTicker = null; stockRefresh.cancel(); stockRefresh = null; stockRefreshTask = null; } // synchronized } /** * <p>When the application management software has determined that the * <code>MIDlet</code> is no longer needed, or perhaps needs to make room * for a higher priority application in memory, is signals * the <code>MIDlet</code> * that it is a candidate to be destroyed by invoking the * <code>destroyApp(boolean)</code> method. In this case, we need to destroy * the <code>RecordEnumeration</code>s so that we don't waste their memory * and close the open <code>RecordStore</code>s. If the * <code>RecordStore</code>s * are empty, then we do not need them to be stored as * they will be recreated * on the next invokation of the <code>MIDlet</code> so * we should delete them. * At the end of our clean up, we must call <code>notifyDestroyed</code> * which will inform the application management software that we are done * cleaning up and have finished our execution and can * now be safely terminated and * enters the <code>Destroyed</code> state.</p> * * @param unconditional If true when this method is called, * the <code>MIDlet</code> must * cleanup and release all resources. If false the <code>MIDlet</code> * may throw <code>MIDletStateChangeException</code> to indicate it * does not want to be destroyed at this time. * @throws <code>MIDletStateChangeException</code> * is thrown if the <code>MIDlet</code> wishes to continue to * execute (Not enter the <code>Destroyed</code> state). This * exception is ignored if <code>unconditional</code> is equal * to true. * @see javax.microedition.midlet.MIDlet */ public void destroyApp(boolean unconditional) throws MIDletStateChangeException { // If there is no criteria that will keep us from terminating if (unconditional) { synchronized (this) { if (display == null) { // If display == null, we are not initialized and // we have nothing to destroy return; } stockRefresh.cancel(); try { stocks.close(); alerts.close(); RecordStore settings = RecordStore.openRecordStore("Settings", true); try { settings.setRecord(1, String.valueOf(refresh_interval) .getBytes(), 0, String.valueOf(refresh_interval) .length()); // First time writing to the settings file } catch (RecordStoreException rse) { settings.addRecord(String.valueOf(refresh_interval) .getBytes(), 0, String.valueOf(refresh_interval) .length()); } settings.closeRecordStore(); } catch (Exception e) { // Ignore exception there is no place to report it } notifyDestroyed(); // Something might make us not want to exit so check it // here before terminating } // synchronized } } /** * <p>Calculate the profits in a What If? scenario by the formula:</p> * <p><type> Profit = (CurrentPrice - OriginalPurchasePrice) * * NumberOfShares</type></p> * <p>First we retrieve the current price of the stock. Then parse the * original purchase price that the user enters to format it to an * integer. Next, retrieve the number of shares from the form that * the user filled in and then calculate the profits and display a nice * message (with the result) to the user onscreen.</p> */ private void calc() { try { String s = stocks.search(stockSymbol); int currPrice = Stock.getPrice(s); int opp = Stock.makeInt(origPurchPriceField.getString()); int numShares = Integer.valueOf(numSharesField.getString()).intValue(); int profit = ((currPrice - opp) * numShares); Form answerForm = new Form(Stock.getName(s) + " " + Stock.getStringPrice(s)); StringBuffer sb = new StringBuffer().append("Net profit (loss) is ") .append((profit >= 0) ? "$" : "($") .append((profit >= 0) ? Stock.convert(profit) : "-" + Stock.convert(profit)) .append((profit >= 0) ? "" : ")") .append(" when selling ") .append(String.valueOf(numShares)) .append(" shares at $") .append(Stock.convert(currPrice)) .append(" per share."); answerForm.append(sb.toString()); answerForm.addCommand(BACK_COMMAND); answerForm.addCommand(MAIN_MENU_COMMAND); answerForm.setCommandListener(new StockCommandListener()); display.setCurrent(answerForm); currentMenu = "AnswerForm"; } catch (Exception e) { error("Calculation Failed", 2000); } } /** * <p>Set an alert for the selected stock at the specified price</p> * * @param Sprice String representation of the price of the stock that * the user would like an alert for */ private void setAlert(String Sprice) { try { alerts.add((new StringBuffer() .append(Stock.getName(stocks.search(stockSymbol))) .append(';') .append(Stock.makeInt(Sprice))).toString()); } catch (Exception e) { error("Failed to add alert", 2000); } } /** * <p>Generate a string (which concatenates all of the stock names and * prices) which will be used for the <code>Ticker</code>.</p> * * @return The ticker string which concatenates all of the stock symbols * and prices */ private String makeTickerString() { // the ticker tape string StringBuffer tickerTape = new StringBuffer(); try { RecordEnumeration re = stocks.enumerateRecords(); while (re.hasNextElement()) { String theStock = new String(re.nextRecord()); tickerTape.append(Stock.getName(theStock)) .append(" @ ") .append(Stock.getStringPrice(theStock)) .append(" "); } } catch (Exception e) { return "Error Accessing Database"; } return tickerTape.toString(); } /** * <p>Display a message onscreen for a specified period of time</p> * * @param message The message to be displayed * @param time The delay before the message disappears */ private void error(String message, int time) { if (!(display.getCurrent() instanceof Alert)) { Alert a = new Alert("Error", message, null, AlertType.ERROR); a.setTimeout(time); display.setCurrent(a, display.getCurrent()); } } /** * <p>Check the alerts to see if any are registered for tkrSymbol at the * tkrSymbol's current price</p> * * @param tkrSymbol The name of the stock to check for alerts on */ private void checkAlerts(String tkrSymbol) { try { int current_price = Stock.getPrice(stocks.search(tkrSymbol)); RecordEnumeration re = alerts.enumerateRecords(tkrSymbol, current_price); while (re.hasNextElement()) { String alert_string = new String(re.nextRecord()); int my_price = Integer.valueOf(alert_string .substring(alert_string.indexOf(';')+1, alert_string.length())) .intValue(); Alert a = new Alert(tkrSymbol, "", null, AlertType.ALARM); StringBuffer sb = new StringBuffer() .append(tkrSymbol) .append(" has reached your price point of $") .append(Stock.convert(my_price)) .append(" and currently is trading at $") .append(Stock.getStringPrice(stocks .search(tkrSymbol))); a.setString(sb.toString()); a.setTimeout(Alert.FOREVER); display.setCurrent(a); alerts.delete(alert_string); } } catch (RecordStoreNotOpenException rsno) { } catch (RecordStoreException rs) { } } /** * <p>Display the main menu of the program</p> */ private void mainMenu() { display.setCurrent(menu); currentMenu = "Main"; } /** * <p>Show the list of stocks to pick from and set the menu type to indicate * to the Listener what to do with the list choice</p> * * @param reload Indicates whether the list should be reloaded * which should * only happen if it is possible that the stocks have changed * since it was last shown * @param menuType Which menu is this list representing * @param type Type of Choice to display * @param prices Indicates whether or not to show prices on the list */ private void chooseStock(boolean reload, String menuType, int type,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -