TweetFollow Us on Twitter

Getting Started with REALBasic-Part 4

Volume Number: 25 (2009)
Issue Number: 01
Column Tag: Programming

Getting Started with REALBasic-Part 4

Designing the Application

by Norman Palardy

REALbasic is a Rapid Application Development (RAD) tool from REALSoftware. In the last column we implemented a big chunk of the database for our stock tracker application. REALbasic 4 and 4.1 have been released in the interim and we'll move up to using that version as there are a number of bug fixes and improvements in it.

Back to it

I've been extremely busy getting the last two releases of REALbasic out and apologize to everyone for the hiatus.

This time the focus is going to be on getting several stocks symbols into the database, retrieving quotes for each of them and storing the data back in the database.

Right now the database is cleaned out every time we start up. While it makes for a nice clean starting point, it's really not that useful in an application that is designed to store data for a long period of time.

We'll need to start by looking at the things that happen when we start up our application. If the database already exists, that's great and we don't need to worry about doing much more. If it doesn't, we need to create it.

But, how are we going to know what database the user wants to use and where it might be?

There are at least a couple ways of dealing with this. One would be to read a preference from some repository like a preferences file and use that. The other would be to use a "well defined place" to store this. Conveniently on OS X and Windows there is a convention for exactly this purpose. On OS X this is in the users Application Data directory. And REALbasic makes it easy to access.

So let's alter the App.Open event to handle all this for us.

// if the Application Data directory has a directory for our app
// and the directory holds our database then we should use that one
if SpecialFolder.ApplicationData.Child(app.kAppName).Exists = true _
and SpecialFolder.ApplicationData.Child(app.kAppName).Child(kDBName).Exists = true then
  app.db.DatabaseFile =  SpecialFolder.ApplicationData.Child(app.kAppName).Child(kDBName)
    app.db = new REALSQLDatabase
    
    app.db.DatabaseFile = SpecialFolder.ApplicationData.Child(app.kAppName).Child(kDBName)
    // see if we can open the database
    if app.db.Connect() <> true then
      // oh oh .... something bad 
      app.db = nil
      msgbox "Unable to connect to database"
      return
    end if
  else
    // hmm is there a directory for our application ?
    if SpecialFolder.ApplicationData.Child(app.kAppName).Exists <> true then
      // no so better create one
      SpecialFolder.ApplicationData.Child(app.kAppName).CreateAsFolder()
    end if
    
    // is there a database ?
    if SpecialFolder.ApplicationData.Child(app.kAppName).Child(app.app.kDBName).Exists <> true then
      
      // no database file
      
      // create a new instance REASQLDatabase Class
      app.db = new REALSQLDatabase
      
      // set the file to the one in the users Library > Application Support
      app.db.DatabaseFile =  SpecialFolder.ApplicationData.Child(app.kAppName).Child(app.kDBName)
      
      // create the container database file
      if app.db.CreateDatabaseFile() <> true then
        
        // something bad      
        app.db = nil
        
        msgbox "Unable to create database"
        
        return 
      else
        
        // ok so now create the database tables
        CreateDBTables()
        
      end if
      
    end if
    
  end if  

As you look this code over you should notice that I've used two constants for the name of the directory, App.kAppName, and the name of the database, App.kDBName.

Add a constant to the App instance in your project and name it kAppName. Set the value for it to MyStockApp. And add the second constant, kDBName, and set its value to "MyStocks.db"

You'll also need to create an empty method in the App instance called CreateDBTables.

We'll fill this one in later.

If you run the app at this point you should find things still work, but you are no longer prompted to select a database. Instead one is automatically place in ~/Library/Application Support/MyStockApp called MyStocks.db.

This is exactly as it should be.

This new database is completely empty though. It doesn't even have the tables we need and this is what we'll fix in the new CreateDBTables method.

But how to get the same definitions we came up with before? It turns out that OS X includes sqlite and we can actually get it to dump out all the SQL we'll need to create the database. Open Terminal.app (located in /Applications/Utilities) and type in

sqlite3

and then drag the database into the terminal window. sqlite will open the database and then you can run the one SQL command needed

select sql from sqlite_master where type = 'table' 

In my case this gives me the exact sql I need to create the tables

CREATE TABLE StocksOfInterest(Name Varchar, Symbol VarChar)
CREATE TABLE StockQuote(Symbol Text, Price Double, quoteDateTime Timestamp)

I can take this and incorporate it into the CreateDBTables method as follows:

  app.db.sqlexecute("CREATE TABLE StocksOfInterest(Name Varchar, Symbol VarChar)")
  app.db.sqlexecute("CREATE TABLE StockQuote(Symbol Text, Price Double, quoteDateTime Timestamp)")

Note that what we have is one language, REALbasic, telling another tool, sqlite, to execute a command in it's language, SQL, that it understands and can do something useful with.

REALbasic does not know anything about SQL. It's just strings of characters to REALbasic.

And SQL knows nothing about REALbasic and it's variables, methods, or anything else.

This is very important to realize that they know nothing about each other and that getting them to work properly together is sometimes and exercise in making sure the string you've created in your REALbasic code IS the right SQL. Sometimes testing things out by hand is the only good way to figure out where your error is if you have trouble. This makes the inclusion of sqlite very handy on OS X.

In fact, let's test this out. If you have a database in ~/Library/Application Support/MyStockApp then delete it and run the program again. Once it has run, quit and then, in Terminal, ahave sqlite3 ope nthe newly created database.

Again use the sql command

select sql from sqlite_master where type = 'table' 

and you should see that there are the two commands that we had in our application to create the tables. We've now created the tables programmatically.

Moving On

Now that we have created the database lets see how we can get quotes into it in an automated way.

I happen to like using Yahoo because the service is easy to grab data from. That said you can probably use whatever service you want. Some will be easier and some more difficult.

What we need to know is how to get the "current" quote from Yahoo for a specific stock in a form we can do something useful with.

Yahoo has a nice simple URL for this exact thing

http://download.finance.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=<symbol>

In a browser if you replace <symbol> with AAPL this will download a file to your machine that is a csv delimited text file with the most recent quote for AAPL. You can alter a number of other attributes to get other data but this is the form we want.

So what we need to do is get REALbasic to go to this URL, get the data and parse it apart and put it in our database and the redisplay the data. And to do this every "once in a while". Nothing to it :)

It turns out that REALbasic has just the thing for this task: the HTTP socket. There are two ways to use this; synchronously and asynchronously. The simpler of the two is synchronously and so that's what we'll use.

But how to get REALbasic to do this "once in a while"? Again, REALbasic has a nice object called a Timer that can be used to do things periodically. Note that timers are "patient" in that they try to work as close to the timing you set but if something else is really busy they will wait until there is a chance for them to do their thing. So they are reasonably accurate in running periodically but not 100% precise.

We'll make use of the timer as it is good enough for what we need.

Open the wStocks window and scroll down the list of controls, select the timer, and drag one onto the workspace.


Figure 1 - Selecting the timer


Figure 2 - Timer placed on Workspace

A timer has several useful properties that we will want to adjust.


Figure 3 - Timer Properties

The Mode property controls whether the timer is on and active or not and if it is one whether the timer runs and performs its action once, or repeatedly. You can toggle this setting in your program as well as setting it directly in the IDE.

The other setting is the Period, or minimum time between the timer performing its action. If the Timer is set to run its action multiple times this will be the minimum time between actions. Careful though, as the period is specified in milliseconds and the setting shown above is only 1 second. We should set this to something more like 300,000, which is every 5 minutes.

Let's make a method that gets the stock data from the web and inserts into the database first.

Open the App instance and create a new method called GetStockPrice. This should take one parameter; the Symbol of the stock we want the quote for. Mine looks like

Sub GetStockPrice(symbol as string)
  dim HTTP as HTTPSocket
  dim data as string
  
  if trim(symbol) = "" then return
  
  // we're going to grab the price from Yahoo
  // the URL is like
  // http://download.finance.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=<symbol>
  dim url as string = "http://download.finance.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol
  
// make a new HTTP socket to use
  http = new HTTPSocket
  
// tell it to get the data and wait no more than 30 seconds for a reply
  data = HTTP.Get(url, 30)
  
  // the data we get back is like
  // "AAPL",117.05,"8/16/2007","4:00pm",-2.85,116.91,118.50,111.62,66667828
  
// pull out the price (the seccond field)
  dim stockPrice as double = val(nthfield(data,",", 2) )
  
// and use our already existing method to put it in the database
  app.AddDataForStock Symbol, stockPrice , new Date
  
End Sub

Now if you double click the Timer we can add the code that will grab the stock quotes every time the timer runs its Action. In the timer simply put

App.GetStockPrice("AAPL")

This will grab the new quotes for AAPL every 5 minutes. But we also want to update the display with those. And eventually we want to be able to make this grab a list of stocks, not just one or two.

First let's deal with displaying the stock quotes.

If you look in the open event for the listbox that shows the stock quotes it has a bunch of code already that we just need to move somewhere else so we can have it redisplay things on demand, not just when the window opens. This is a perfect opportunity to refactor this code so it's more generally useful.

Start by creating a new method called ReDisplayData.

Take all the code from the Open Event of the listbox and move it into this new method. You'll have to change every place it says "me." to "lstStocks."

Then, in the Listbox open event simply have it call ReDisplayData so it looks like

  RedisplayData()

And add a call to RedisplayData at the end of the timer's actions as well so it looks like

  GetStockPrice("AAPL")

  RedisplayData()

If you run now you should see the display get a new entry for AAPL every few minutes. However, the display of the stock proce might look a little odd. On mine, as of this writing it shows "9.74000000056e+1".

So lets change Redisplay data a little.

If you look at the line that reads

lstStocks.Cell(lstStocks.LastIndex,2) = rs.Field("Price").StringValue

and change it to

lstStocks.Cell(lstStocks.LastIndex,2) = Format(rs.Field("Price").DoubleValue,"#.00")

This will make things look right. The original line just used an implicit conversion of a floating point double to a string. The default is to give you scientific notation. The FORMAT command gives us control over how the conversion to a string occurs and so it looks better.

Lots of Progress

Just in this short sprint we've made a lot of progress. We've made the application create it's own database if none existed. We've added the ability to periodically grab new quotes from the internet and redisplay them. And, when you quit and restart your application it will start up with all the data you had before. Not bad for this time around.

There are some things you might want to look into until next time.

ReDisplayData just keeps adding to the list shown all the time and so if you leave this application running for a long time it will eventually have an enormously long list of items displayed. You might see if you can chnage that.

And for the really adventurous, see if you can change JUST the SQL that ReDisplayData uses so it only grabs the latest quote instead of all of them.


Norman Palardy has worked with SQL databases since 1992, and has programmed in C, C++, Java, REALbasic and other languages on a wide variety of platforms. In his 15+ years of IT experience, Norman has developed innovative and award-winning applications for TransCanada Pipelines, Minerva Technologies (now XWave), Zymeta Corporation, and the dining and entertainment industry. He holds a BSc from the University of Calgary in Alberta. He's also a founder of the Association of REALbasic Professionals (http://www.arbp.org) and currently works for REAL Software

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.