KJava中投资报价持久存储的实现
立即解锁
发布时间: 2025-08-18 02:20:33 阅读量: 1 订阅数: 5 

### KJava 中投资报价持久存储的实现
在投资应用程序中,存储和检索股票或共同基金的报价数据是非常重要的功能。本文将详细介绍如何在 KJava 中实现投资报价的持久存储,包括数据存储格式、存储和检索记录的方法,以及如何连接到互联网获取实时报价。
#### 1. 数据存储格式
为了存储股票或共同基金的当前价格和历史价格,我们需要将这些数据转换为字符串格式,并使用分号作为分隔符。例如,对于 3M 公司的当前价格为 $120.55,历史价格为 $113.45,存储的字符串格式如下:
```
MMM;120;55;113;45
```
如果只获取到一个价格,则最后两个整数可以省略。例如,当第一次获取到 3M 公司的价格为 $113.45 时,记录字符串为:
```
MMM;113;45
```
在将字符串记录存储到数据库之前,需要将其转换为字节数组。可以使用 `String` 对象的 `getBytes()` 方法来实现。
#### 2. 存储投资报价
`ObtainQuoteSpotlet` 类负责控制获取和存储股票或共同基金报价的所有方面。在用户界面章节中,我们使用任意数字来模拟获取价格。现在,我们的目标是实现价格数据的存储,以便后续由 `RetrieveQuoteSpotlet` 类使用。
为了存储价格数据,我们需要一个打开的 Palm OS 数据库。我们创建一个名为 `storePrice(String symbol, int[] price)` 的新方法,该方法将实现保存价格的用例。以下是该方法的实现:
```java
private void storePrice(String symbol, int[] price) {
String newRecord = symbol + ";" + price[0] + ";" + price[1];
byte[] byteRec;
String dbName = "QuoteData";
int dbType = 0x494E5653; //'INVS'
int dbCreator = 0x43415454; //'CATT'
com.sun.kjava.Database quoteDB = new Database (dbType, dbCreator, Database.READWRITE);
if (!quoteDB.isOpen()) {
Database.create(0, dbName, dbCreator, dbType, false);
quoteDB = new Database (dbType, dbCreator, Database.READWRITE);
}
boolean found = false;
int n = quoteDB.getNumberOfRecords();
for (int i = 0; i < n; i++) {
byte[] raw = quoteDB.getRecord(i);
if ((new String(raw)).startsWith(symbol + ';')) {
found = true;
newRecord += ';' + getLastPrice(raw);
byteRec = newRecord.getBytes();
quoteDB.setRecord(i, byteRec);
break;
}
}
if (!found) {
byteRec = newRecord.getBytes();
quoteDB.addRecord(byteRec);
}
quoteDB.close();
}
```
在上述代码中,我们首先打开或创建一个名为 `QuoteData` 的数据库。然后,遍历数据库中的所有记录,检查是否存在与给定符号匹配的记录。如果找到匹配的记录,则更新该记录,将最后一个当前价格作为新的历史价格。如果未找到匹配的记录,则添加一个新记录。最后,关闭数据库。
为了提取现有记录中的最后一个价格,我们创建了一个名为 `getLastPrice(byte[] rec)` 的辅助方法:
```java
private String getLastPrice(byte[] rec) {
String recString = new String(rec);
int dollarPos = recString.indexOf(';');
int centPos = recString.indexOf(';', dollarPos + 1);
int centEnd = recString.indexOf(';', centPos + 1);
if (centEnd > 0) // 有历史价格
return recString.substring(dollarPos + 1, centEnd);
else // 没有历史价格
return recString.substring(dollarPos + 1);
}
```
在 `ObtainQuoteSpotlet` 类的 `penDown()` 方法中,当用户点击 “Get Quote” 按钮时,调用 `storePrice()` 方法存储价格数据:
```java
if ((symbolField.getText().length() > 0) && (checkSymbol())) {
Graphics.playSound(Graphics.SOUND_STARTUP);
String sym = symbolField.getText().toUpperCase();
// 稍后从报价服务获取价格
int[] price = {75, 55};
storePrice(sym, price);
resultsBox.setText("The price of " + sym + " is $" + price[0] + "." + price[1]);
resultsBox.paint();
}
```
#### 3. 检索记录
`RetrieveQuoteSpotlet` 类负责从数据库中检索存储的报价,并显示当前和历史价格。为了实现这一功能,我们创建了一个名为 `retrievePrices(String symbol)` 的方法:
```java
private int[] retrievePrices(String symbol) {
int[] dollars = null;
String dbName = "QuoteData";
int dbType = 0x494E5653; //'INVS'
int dbCreator = 0x43415454; //'CATT'
com.sun.kjava.Database quoteDB = new Database (dbType, dbCreator, Database.READWRITE);
if (!quoteDB.isOpen()) {
Database.create(0, dbName, dbCreator, dbType, false);
quoteDB = new Database (dbType, dbCreator, Database.READWRITE);
}
boolean found = false;
int n = quoteDB.getNumberOfRecords();
for (int i = 0; i < n; i++) {
String raw = new String(quoteDB.getRecord(i));
if (raw.startsWith(symbol + ';')) {
found = true;
byte[] rec = quoteDB.getRecord(i);
dollars = parsePrices(rec);
break;
}
}
if (!found) {
dollars = null;
}
quoteDB.close();
return dollars;
}
```
在上述代码中,我们打开或创建数据库,遍历所有记录,查找与给定符号匹配的记录。如果找到匹配的记录,则调用 `parsePrices(byte[] quoteRec)` 方法提取当前和历史价格:
```java
private int[] parsePrices(byte[] quoteRec) {
String rec = new String(quoteRec);
int dollar1Pos = rec.indexOf(';');
int cent1Pos = rec.indexOf(';', dollar1Pos + 1);
int dollar2Pos = rec.indexOf(';', cent1Pos + 1);
if (dollar2Pos > 0) { // 有历史价格
int cent2Pos = rec.indexOf(';', dollar2Pos + 1);
int currentDollars = Integer.parseInt(rec.substring(dollar1Pos + 1, cent1Pos));
int currentCents = Integer.parseInt(rec.substring(cent1Pos + 1, dollar2Pos));
int historicalDollars = Integer.parseInt(rec.substring(dollar2Pos + 1, cent2Pos));
int historicalCents = Integer.parseInt(rec.substring(cent2Pos + 1));
int[] returnPrices = {currentDollars, currentCents, historicalDollars, historicalCents};
return returnPrices;
} else { // 没有历史价格
int currentDollars = Integer.parseInt(rec.substring(dollar1Pos + 1, cent1Pos));
int currentCents = Integer.parseInt(rec.substring(cent1Pos + 1));
int[] returnPrices = {currentDollars, currentCents};
return returnPrices;
}
}
```
在 `RetrieveQuoteSpotlet` 类的 `displayChart()` 方法中,当用户点击 “Get Quote” 按钮时,调用 `retrievePrices()` 方法获取价格数据并显示:
```java
private void displayChart(String currentSymbol) {
int[] prices = retrievePrices(currentSymbol);
if (prices != null) {
if (prices.length > 2) {
paintChart(currentSymbol, prices[0], prices[2]);
} else {
Graphics.drawRectangle(5, 60, 155, 70, Graphics.ERASE, 0);
Graphics.drawString("Recorded price for " + currentSymbol + " is: $" + prices[0] + "." + prices[1], 5, 65, Graphics.PLAIN);
Graphics.drawString("No historical data exists.", 5, 80, Graphics.INVERT);
}
} else {
Graphics.playSound(Graphics.SOUND_ERROR);
Dialog noDataAlert = new Dialog(this, "Alert", "No price exists for " + currentSymbol, "OK");
noDataAlert.showDialog();
}
}
```
#### 4. 连接到互联网
为了获取实时投资报价,我们需要将 `ObtainQuoteSpotlet` 类连接到互联网。在 MIDP 版本的教程应用程序中,我们实现了一个 `QuoteService` 类来连接到互联网并获取报价。由于 KJava 运行在 CLDC 之上,并且 `QuoteService` 类的实现尽可能通用,因此我们可以直接重用该服务。
在 `ObtainQuoteSpotlet` 类的 `penDown()` 方法中,将获取价格的代码替换为调用 `QuoteService` 类的 `getPrice()` 方法:
```java
if ((symbolField.getText().length() > 0) && (checkSymbol())) {
Graphics.playSound(Graphics.SOUND_STARTUP);
String sym = symbolField.getText().toUpperCase();
int type;
if (investmentChoice.getSelected().equals(fundButton))
type = 1;
else
type = 0;
int[] price = QuoteService.getPrice(sym, type);
if (price != null) {
storePrice(sym, price);
resultsBox.setText("The price of " + sym + " is $" + price[0] + "." + price[1]);
resultsBox.paint();
} else {
Graphics.playSound(Graphics.SOUND_ERROR);
Dialog symbolAlert = new Dialog(this, "Alert", "Check Symbol and Type.\n\nNo quote found.", "OK");
```
0
0
复制全文
相关推荐










