How to solve the ACCESS VIOLATION problem in the OnNotify event of Generics Lists? [duplicate]

  

This question already has an answer here:

Delphi: Access Violation at the end of Create() constructor

2 answers

How to solve the ACCESS VIOLATION problem in the OnNotify event of Generics Lists?

I’ve created this example below and the error is pointed out with comment (on FormCreate).
I have already seen this post HERE and followed the guidelines, but it didn’t solve the problem.

The code compiles correctly, but gives an error when running the program.

unit Unit1;

interface

uses
System.SysUtils, System.Types, System.UITypes, System.Generics.Collections,
System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms,
FMX.Graphics, FMX.Dialogs, System.Bluetooth, FMX.Controls.Presentation,
FMX.StdCtrls;

type
TForm1 = class(TForm)
btCreateList: TButton;
btDestroyList: TButton;
procedure btCreateListClick(Sender: TObject);
procedure btDestroyListClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure OnBLENotify(Sender: TObject; const Item: TBluetoothLEDevice;
Action: System.Generics.Collections.TCollectionNotification);
end;

var
Form1: TForm1;
list: TBluetoothLEDeviceList;
ble: TBluetoothLEDevice;

implementation

{$R *.fmx}

procedure TForm1.btCreateListClick(Sender: TObject);
var i: Integer;
begin
for i := 0 to 4 do begin
ble := TBluetoothLEDevice.Create(False);
list.Add(ble);
end;
end;

procedure TForm1.btDestroyListClick(Sender: TObject);
begin
list.DisposeOf;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
list.Create; // <<<<<<========== ACCESS VIOLATION HERE
list.OnNotify := OnBLENotify;
end;

procedure TForm1.OnBLENotify(Sender: TObject; const Item: TBluetoothLEDevice;
Action: System.Generics.Collections.TCollectionNotification);
begin
ShowMessage(item.DeviceName);
end;

end.

Comments are closed.