Local Storage Demo 3

On first run this version saves an array of strings as a single string and an array of numbers as another string. On subsequent runs the program reads the two saved strings, converts them back to arrays, then outputs the contents of each array. We demonstrate the Smart Pascal procedures strJoin and strSplit which are useful for converting an array to a string and then regenerating the array.

unit Unit1;

interface

uses 
  System.Types, System.Lists, SmartCL.System, SmartCL.Scroll, SmartCL.Console,
  SmartCL.Components, SmartCL.Application, SmartCL.ConsoleApp, SmartCL.Storage;

type
  TApplication = class(TW3CustomConsoleApplication)
  private
    FStorage: TW3LocalStorage;
    FColours : array of string;
    FColours2 : array of string;
    FstrColours, FstrRainfall : string;
    FRainfall : array[0 .. 11] of integer := [61, 36, 50, 42, 45, 46, 46, 44, 43, 73, 45, 59];
    FRainfallStringArray : array of string;
    FRainfall2 : array of integer;
  protected
    procedure ApplicationStarting; override;
    procedure PopulateConsole; override;
    procedure ApplicationClosing; override;
  end;

implementation

procedure TApplication.ApplicationStarting;
var
  i : integer;
begin
  FColours := ['aqua', 'black', 'blue', 'fuchsia', 'green', 'gray',
              'lime', 'maroon', 'navy', 'olive', 'purple', 'red',
              'silver', 'teal', 'white', 'yellow'];
  FstrColours := strJoin(FColours, ',');
  FstrRainfall := '';
  for i := 0 to 10 do
    FstrRainfall += FRainfall[i].ToString + ',';
  FstrRainfall += FRainfall[11].ToString;

  FStorage := TW3LocalStorage.Create;
  FStorage.Open('Demo3');
  inherited;
end;

procedure TApplication.PopulateConsole;
var
  s: String;
  i: integer;
begin
  s := FStorage.getKeyStr('saved', 'error');
  if s = 'error' then
    begin
      FStorage.setKeyStr('saved', 'true');
      Console.WriteLn('Saving strings and numbers.');
      FStorage.setKeyStr('Colours', FstrColours);
      FStorage.setKeyStr('Rainfall', FstrRainfall);
    end
  else
    begin
      FstrColours := FStorage.getKeyStr('Colours', 'error');
      FColours2 := strSplit(FstrColours, ',');
      for i := 0 to 15 do
        Console.WriteLn(FColours2[i] + ' ');

      FstrRainfall := FStorage.getKeyStr('Rainfall', 'error');
      FRainfallStringArray := strSplit(FstrRainfall, ',');
      for i := 0 to 11 do
        begin
          FRainfall2[i] := FRainfallStringArray[i].ToInteger;
          Console.WriteLn(FRainfall2[i].ToString);
        end
    end;
end;

procedure TApplication.ApplicationClosing;
begin
  FStorage.Close;
  inherited;
end;

end.

    
Programming - a skill for life!

Storage and retrieval of data using local storage, cookies, HTTP and MySQL