从sqlite填充数组

问题描述 投票:1回答:1

我想从sqlite数据库填充数组。

我用数据库填充了数据,但是我无法查看数组内的数据以再次在listview中查看它。

请注意,列表视图由(Heading,SubHeading)内部的视图组成。

  public  List<TableItem> tableitems;

 public void fillarray()
        {
           var db = new SQLiteConnection(dbPath);
            tableitems = new List<TableItem>();
            var table = db.Table<SqliteDB.Departments>();
          foreach (var s in table)
            {
             new TableItem() { Heading = s.Id.ToString(), SubHeading = s.FullName.ToString() };
            }
           }
xamarin.android
1个回答
1
投票

根据您的代码,您在sqlite数据库中有一个表名Departments,您想要从该表中获取数据,并将这些数据填充到表项中并显示到ListView中,对吗?

如果是,则需要执行两个步骤,首先需要从sqlite数据库获取数据,其次需要在ListView中创建自定义行以显示表项。

 private SQLiteConnection db;
 private List<TableItem> items;

 private void Btnget_Click(object sender, System.EventArgs e)
    {
       string dpPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Persons.db3");
       db = new SQLiteConnection(dpPath);
       foreach(var de in db.Table<Departments>())
        {
            TableItem item = new TableItem();
            item.Heading = de.id.ToString();
            item.SubHeading = de.FullName;
            items.Add(item);
        }

        listview1.Adapter = new ListViewAdapter(this,items);
    }

ListView中的自定义行:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:id="@+id/textView1"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:id="@+id/textView2"/>
</LinearLayout>

ListViewAdapter.cs:

 public class ListViewAdapter : BaseAdapter<TableItem>
{
    List<TableItem> items;
    Activity context;

    public ListViewAdapter(Activity context, List<TableItem> items) :base()
    {
        this.context = context;
        this.items = items;
    }
    public override TableItem this[int position]
    {
        get { return items[position]; }
    }

    public override int Count
    {
        get { return items.Count; }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = items[position];

        View view = convertView;
        if (view == null) // no view to re-use, create new
            view = context.LayoutInflater.Inflate(Resource.Layout.CustomRow, null);
        view.FindViewById<TextView>(Resource.Id.textView1).Text = item.Heading;
        view.FindViewById<TextView>(Resource.Id.textView2).Text = item.SubHeading;


        return view;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.