How to download Images without freeze or crash Delphi app

  

I have this code. Make a PHP Query to server and the results are Image URLs.
I try to put them to a Listbox, in a TImage in ListboxItems with AnonymousThread and loop. All good on Windows but on Android the app crash.
procedure TForm10.Button1Click(Sender: TObject);
var
aJSONArray: TJSOnArray;
ThumbUrl, Postid: String;
PCount: integer;
begin
ListBox1.Items.Clear;
Edit1.Text := ”;

TThread.CreateAnonymousThread(
procedure
begin
aJSONArray := TJSOnArray.Create;
aJSONArray := TJSONObject.ParseJSONValue(TEncoding.ASCII.
GetBytes(NetHTTPClient1.Get(‘https://server/getUserPhotos.php?userid=1’).
ContentAsString), 0) as TJSONArray;

TThread.Synchronize(nil,
procedure
var
AI: Integer;
LBI: TListBoxItem;
img: TImage;
begin
ListBox1.ItemHeight := ((ListBox1.Width / 3)-2);
ListBox1.ItemWidth := ((ListBox1.Width / 3)-2);
for AI := 0 to (aJSONArray.Count -1) do
begin
ListBox1.BeginUpdate;
ThumbUrl := (aJSonArray.Items[AI].GetValue<string>(‘image_url_150’));
Postid := (aJSonArray.Items[AI].GetValue<string>(‘post_id’));
if ThumbUrl <> ” then
begin
LBI := TListBoxItem.Create(Self);
LBI.Parent := ListBox1;
try
img := TImage.Create(self);
img.Parent := ListBox1.ItemByIndex(AI);
img.Align := TAlignLayout.Client;
img.WrapMode := TImageWrapMode.Fit;
with img.Margins do
begin
Left := 1;
Right := 1;
Top := 1;
Bottom := 1;
end;
img.Tag := StrToInt(Postid);
img.TagString := ThumbUrl;
img.OnPainting := imgPainting;
finally
ListBox1.EndUpdate;
end;
end;
end;
end);
aJSONArray.Free;
end).Start;
end;

procedure TForm10.imgPainting(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
var
AStream: TMemoryStream;
begin

TThread.CreateAnonymousThread(
procedure
begin
try
AStream := TMemoryStream.Create;
NetHTTPClient1.Get(TImage(Sender).TagString, AStream);
AStream.Position := 0;

TThread.Synchronize(nil,
procedure
begin
TImage(Sender).Bitmap.LoadFromStream(AStream);
end);
finally
AStream.Free;
end;
end).Start;
end;

I try to download images in the loop but the app freezes until all images are downloaded. What goes wrong?

Comments are closed.