How To Add List to Local Database? and images As it even cannot take the ImageSource?

khixr111khixr111 Member ✭✭

public ImageSource Image1 { get; set; }
public ImageSource Image2 { get; set; }
public ImageSource Image3 { get; set; }
public ImageSource Image4 { get; set; }
public ImageSource Image5 { get; set; }
public ImageSource Image6 { get; set; }
public ImageSource Image7 { get; set; }
public ImageSource Image8 { get; set; }
public ImageSource Image9 { get; set; }
public ImageSource Image10 { get; set; }
public ImageSource Image11 { get; set; }

Tagged:

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    How To Add List to Local Database?

    Try SQLite-Net Extensions. Define the classes like:

    public class ImageManager
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
    
        public byte[] Image { set; get; }
    
        [TextBlob(nameof(NamesBlobbed))]
        public List<string> Names { set; get; }
        public string NamesBlobbed { set; get; }
    }
    

    Then use InsertWithChildren to store your object:

    var sampleList = new List<string>();
    for (int i = 0; i < 10; i++)
    {
        sampleList.Add("Name" + i);
    }
    
    var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var dbPath = Path.Combine(folderPath, "images.db");
    using (SQLiteConnection conn = new SQLiteConnection(dbPath))
    {
        conn.CreateTable<ImageManager>();
    
        ImageManager imgManager = new ImageManager { Names = sampleList };
    
        conn.InsertWithChildren(imgManager);
    }
    

    Retrieve it like:

    var dbPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    dbPath = Path.Combine(dbPath, "images.db");
    using (SQLiteConnection conn = new SQLiteConnection(dbPath))
    {
        conn.CreateTable<ImageManager>();
        var items = conn.GetAllWithChildren<ImageManager>().ToList();
    }
    

    images As it even cannot take the ImageSource?

    Convert them to bytes firstly. Then store them to your local database:

    var client = new HttpClient();
    var stream = await client.GetStreamAsync("https://sample-videos.com/img/Sample-jpg-image-50kb.jpg");
    
    byte[] bytes;
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        bytes = memoryStream.ToArray();
    }
    
    var sampleList = new List<string>();
    for (int i = 0; i < 10; i++)
    {
        sampleList.Add("Name" + i);
    }
    
    var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var dbPath = Path.Combine(folderPath, "images.db");
    using (SQLiteConnection conn = new SQLiteConnection(dbPath))
    {
        conn.CreateTable<ImageManager>();
    
        ImageManager imgManager = new ImageManager { Image = bytes, Names = sampleList };
    
        conn.InsertWithChildren(imgManager);
    }
    
Sign In or Register to comment.