Search code examples
androiddelphifiremonkeydelphi-xe6

Dynamic Loadfrom file image is giving Access vailation on Firemonkey Mobile


I am creating Demo application that having list box and image. When I am running that application on Phone is giving me (using image1.loadfromfile('Path of Image')) segmentation 11 exception. I am not able to display image which are adding at run time on my Phone. I am using below code for dynamic loading image.

procedure TForm1.Button1Click(Sender: TObject);
var
 item : TListBoxItem;
 img  : Timage;
begin
  item := TListBoxItem.Create(ListBox1);
  img := TImage.Create(item);
  with item do
  begin
    Text := 'Vikas';
    Height := 49;
    Selectable := False;
    StyleLookup := 'listboxitemnodetail';
    img.Align := TAlignLayout.Left;
   end;
    img.MultiResBitmap.Items[0].Bitmap.LoadFromFile('path image in .png format');
    item.AddObject(img); 
    listbox1.addobject(item);
end;

How to load image dynamically?


Solution

  • You need to call the img.MultiResBitmap.Add() method before you can access img.MultiResBitmap.Items[0]:

    Creates a new TCustomBitmapItem bitmap item and adds it to the Items array.

    For example:

    img.MultiResBitmap.Add;
    // now you can use img.MultiResBitmap.Items[0] as needed...
    

    Alternatively:

    var
      bmp: TFixedBitmapItem;
    begin
      ...
      bmp := img.MultiResBitmap.Add;
      // use bmp as needed...
      ...
    end;
    

    If you do not actually need multi-resolution images, use the img.Bitmap property instead:

    img.Bitmap.LoadFromFile(...);