Introduction
In this blog, we will see how to create an SQLite database in Xamarin Android application. We will also see how to add records to the different tables in the same database and read and display that data in an application.
Step1
Create 2 table classes and join and retrieve a separate class linking them,
- public class Person
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public DateTime Dob { get; set; }
- }
- public class Work
- {
- public int PersonId { get; set; }
- public string WorkName { get; set; }
- }
- public class joining
- {
- public List<Person> Personss{ get; set; }
- public List<Work> Works { get; set; }
- }
Step 2
To retrieve a join, use the joining class like below.
- public static List<joining> GetPW(Context context)
- {
- List<Person> people = new List<Person>();
- List<Work> peoplew = new List<Work>();
- SQLiteDatabase db = new DataStore(context).ReadableDatabase;
- string[] column = new string[] { ColumnID, ColumnName, ColumnDob };
- string[] columns = new string[] { ColumnID, ColumnNamew};
- using (ICursor cursor = db.Query(TableName, column, null, null, null, null, null))
- {
- while (cursor.MoveToNext())
- {
- people.Add(new Person
- {
- Id = cursor.GetInt(cursor.GetColumnIndexOrThrow(ColumnID)),
- Name = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnName)),
- Dob = DateTime.Parse(cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnDob)))
- });
- }
- }
- using (ICursor cursor = db.Query(TableNamew, columns, null, null, null, null,null))
- {
- while (cursor.MoveToNext())
- {
- peoplew.Add(new Work
- {
- PersonId = cursor.GetInt(cursor.GetColumnIndexOrThrow(ColumnID)),
- WorkName = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnNamew))
- });
- }
- }
- List<joining> lstJoin = new List<joining>() { new joining { Personss = people, Works = peoplew } };
- return lstJoin;
- }
Step3
To retrieve in MainActivity, use the below code.
- var peoplew = GetPW(this);
- Toast.MakeText(this, $"{peoplew[0].Works[0].WorkName} \n {peoplew[0].Personss[0].Name} people found.", ToastLength.Short).Show();
I have attached the sample application. If any one knows how to use joins in SQLITE-net PCL, please let me know.