Add to listbox or memo from thread delphi

149 views Asked by At

Why I can't add to list box or memo when I execute this thread? Also I can't read form components like TEdit, I get empty string? I tried to put the thread in Synchronize but it's also not working. I need to use the thread to stop application freezing when sending HTTP request. Where is my fault?

procedure Search4Contacts.Execute;
var
  Http: TIdHTTP;
  SSL: TIdSSLIOHandlerSocketOpenSSL;
  JsonRespnse, strIdValue, strAPIUrl, strOauthAccess_Token: string;
  IsConnect, SearchValueIsTrue: boolean;
  jsonObiekt, jsonObiekt_Array: TJSONObject;
  jsonArray: TJSONArray;
  SearchValue, SearchIDValue, SearchNameValue, SearchEmailValue,
    SearchImageValue: TJSONValue;
  HttpRequests_FormData: TIdMultiPartFormDataStream;
  I: integer;
  ListBoxItem: TListBoxItem;
  image: TImage;
  label_1: TLabel;
begin
  IsConnect := True;
  Http := TIdHTTP.Create(nil);
  SSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  HttpRequests_FormData := TIdMultiPartFormDataStream.Create;
  try
    try
      HttpRequests_FormData.AddFormField('name', searchForContactsEdit.Text,
        'utf-8').ContentTransfer := '8bit';
      SSL.SSLOptions.Method := sslvTLSv1;
      SSL.SSLOptions.Mode := sslmUnassigned;
      SSL.SSLOptions.VerifyMode := [];
      SSL.SSLOptions.VerifyDepth := 0;
      Http.IOHandler := SSL;
      Http.HandleRedirects := False;
      Http.Request.CacheControl := 'no-store';
      Http.ProtocolVersion := pv1_1;
      Http.Request.Connection := 'KeepAlive';
      Http.response.KeepAlive := False;
      Http.MaxAuthRetries := 3;
      Http.HTTPOptions := [hoKeepOrigProtocol, hoForceEncodeParams];
      Http.Request.UserAgent := UserAgent;
      JsonRespnse := Http.Post(TIdURI.URLEncode(strAPIUrl),
        HttpRequests_FormData);
    except
      on E: Exception do
      begin
        Memo1.Lines.Add(' "HttpRequests: ' + E.Message);
        IsConnect := False;
      end;
    end;
  finally
    try
      Http.Disconnect;
    except
    end;
    HttpRequests_FormData.Free;
    Http.Free;
    SSL.Free;
  end;

  Memo1.Lines.Add(JsonRespnse);  /// this code did not perform.

  if (IsConnect = True) then
  begin
    if JsonRespnse <> '' then
    begin
      jsonObiekt := TJSONObject.ParseJSONValue
        (TEncoding.ASCII.GetBytes(JsonRespnse), 0) as TJSONObject;
      try
        try
          SearchValue := jsonObiekt.Get('status').JsonValue;
          SearchValueIsTrue := StrToBool(SearchValue.Value);
          if SearchValueIsTrue = True then
          begin
            ContactsListBox.BeginUpdate;
            jsonArray := jsonObiekt.GetValue('items') as TJSONArray;

            Memo1.Lines.Add(jsonArray.ToString);
            for I := 0 to jsonArray.Count - 1 do
            begin
              jsonObiekt_Array := jsonArray.Items[I] as TJSONObject;
              // Memo1.Lines.Add(jsonObiekt_Array.ToString);
              if jsonObiekt_Array is TJSONObject then
              begin
                SearchIDValue := TJSONObject(jsonObiekt_Array).Get('id')
                  .JsonValue;
                SearchNameValue := TJSONObject(jsonObiekt_Array).Get('name')
                  .JsonValue;
                SearchEmailValue := TJSONObject(jsonObiekt_Array).Get('email')
                  .JsonValue;
                SearchImageValue := TJSONObject(jsonObiekt_Array).Get('image')
                  .JsonValue;

                Memo1.Lines.Add('items.id: ' + SearchIDValue.Value);
                // This is not work
                Memo1.Lines.Add('items.name: ' + SearchNameValue.Value);
                // This is not work
                Memo1.Lines.Add('items.email: ' + SearchEmailValue.Value);
                // This is not work
                Memo1.Lines.Add('items.image: ' + SearchImageValue.Value);
                // This is not work

                strUrlPublic := SearchImageValue.Value;
                loadimage(SearchImageValue.Value);
                /// ///////////////////////////////////////////////////////////
                /// ////////////////////////////////////////////////////////////
                ListBoxItem := TListBoxItem.Create(ContactsListBox);
                image := TImage.Create(ListBoxItem);
                label_1 := TLabel.Create(ListBoxItem);

                ListBoxItem.Parent := ContactsListBox;
                ListBoxItem.Size.Height := 40;

                image.Align := TAlignLayout.Left;
                image.Bitmap.LoadFromStream(ContactsIMGStream);
                DestroyImageStream;
                label_1.Align := TAlignLayout.Left;
                label_1.Width := 150;
                ListBoxItem.AddObject(image);
                ListBoxItem.AddObject(label_1);
                // ListBoxItem.text := Buffer;
                label_1.Text := SearchNameValue.Value;
                ContactsListBox.AddObject(ListBoxItem);
              end;
            end;
            ContactsListBox.EndUpdate;

          end;
        except
          on E: Exception do
            ShowMessage('Read JSON : ' + E.Message);
        end;
      finally
        jsonObiekt.Free;
      end;
    end;
  end
  else
  begin
    // re-try login function;
  end;

And here, how I call the thread:

searchContacts := Search4Contacts.Create(True);
try
  searchContacts.FreeOnTerminate := True;
  searchContacts.Priority := tpHighest;
  searchContacts.processType := 'search';
finally
  searchContacts.Start;
end;
0

There are 0 answers