Xamarin : SQLite Local Database
Xamarin : SQLite - Local Database
1. Install "SQLite.Net-PCL" package using nuget package manager. Install in all projects in solution.
2. Create service signature using interface.
using SQLite.Net; namespace App_LocalDataBase { public interface ISQLite { SQLiteConnection GetConnection(); } }
3. Create service manager to implement Interface method.
For Android
using System; using Xamarin.Forms; using LocalDataBase.Droid; using System.IO; [assembly: Dependency(typeof(SqliteService))] namespace App_LocalDataBase.Droid { public class SqliteService : ISQLite { public SqliteService() { } public SQLite.Net.SQLiteConnection GetConnection() { var sqliteFilename = "SQLiteEx.db3"; string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder var path = Path.Combine(documentsPath, sqliteFilename); Console.WriteLine(path); if (!File.Exists(path)) File.Create(path); var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid(); var conn = new SQLite.Net.SQLiteConnection(plat, path); // Return the database connection return conn; } } }
4. Create class in Droid project implement
using LocalDataBase.iOS; using System; using System.IO; using Xamarin.Forms; [assembly: Dependency(typeof(SqliteService))] namespace App_LocalDataBase.iOS { public class SqliteService : ISQLite { public SqliteService() { } public SQLite.Net.SQLiteConnection GetConnection() { var sqliteFilename = "SQLiteEx.db3"; string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder var path = Path.Combine(libraryPath, sqliteFilename); // This is where we copy in the prepopulated database Console.WriteLine(path); if (!File.Exists(path)) { File.Create(path); } var plat = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS(); var conn = new SQLite.Net.SQLiteConnection(plat, path); // Return the database connection return conn; }
} }
5. Write database operation methods in PCL project. Create class name - DataAccess
using SQLite.Net; using Xamarin.Forms; namespace App_LocalDataBase { public class DataAccess { SQLiteConnection dbConn; public DataAccess() { dbConn = DependencyService.Get<ISQLite>().GetConnection(); // create the table(s) dbConn.CreateTable<Employee>(); } public List<Employee> GetAllEmployees() { return dbConn.Query<Employee>("Select * From [Employee]"); } public int SaveEmployee(Employee aEmployee) { return dbConn.Insert(aEmployee); } public int DeleteEmployee(Employee aEmployee) { return dbConn.Delete(aEmployee); } public int EditEmployee(Employee aEmployee) { return dbConn.Update(aEmployee); } } }
6. Create table model in PCL project.
using SQLite.Net.Attributes; using System; namespace App_LocalDataBase { public class Employee { [PrimaryKey, AutoIncrement] public long EmpId { get; set; } [NotNull] public string EmpName { get; set; } public string Designation { get; set; } public string Department { get; set; } public string Qualification { get; set; } } }
7. Create the static object property of ‘DataAccess‘ in ‘App‘ class
using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace App_LocalDataBase { public class App : Application { static DataAccess dbUtils; public App() { // The root page of your application MainPage = new NavigationPage(new ManageEmployee()); } public static DataAccess DAUtil { get { if (dbUtils == null) { dbUtils = new DataAccess(); } return dbUtils; } } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
8. Now its turn to create CRUD operation
- Manage Employees (ManageEmployee.xaml)
- Add Employee (AddEmployee.xaml)
- Show Employee Details ShowEmplyee.xaml
- Edit Employee (EditEmployee.xaml)
Design
<ContentPage.Padding> <OnPlatform x:TypeArguments="Thickness" iOS="0, 20, 0, 0" /> </ContentPage.Padding> <ContentPage.Content> <ListView x:Name="lstData" HasUnevenRows="false" Header="Header Value" Footer="Footer" ItemSelected="OnSelection" > <ListView.HeaderTemplate> <DataTemplate> <StackLayout Orientation="Horizontal" BackgroundColor="Blue" Padding="5,5,5,5"> <Label Text="Name" FontSize="Medium" FontAttributes="Bold" TextColor="White"/> <Label Text="Designation" FontSize="Medium" FontAttributes="Bold" TextColor="White"/> <Label Text="Department" FontSize="Medium" FontAttributes="Bold" TextColor="White"/> </StackLayout> </DataTemplate> </ListView.HeaderTemplate> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Orientation="Horizontal" Padding="5,5,5,5"> <Label Text="{Binding EmpName}" FontSize="Medium" /> <Label Text="{Binding Designation}" FontSize="Medium" /> <Label Text="{Binding Department}" FontSize="Medium" /> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> <ListView.FooterTemplate> <DataTemplate> <StackLayout Orientation="Horizontal" Padding="5,5,5,5"> <Button Text="Add New Employee" Clicked="OnNewClicked" /> </StackLayout> </DataTemplate> </ListView.FooterTemplate> </ListView> </ContentPage.Content>
Code
public ManageEmployee() { InitializeComponent(); var vList = App.DAUtil.GetAllEmployees(); lstData.ItemsSource = vList; } void OnSelection(object sender, SelectedItemChangedEventArgs e) { if (e.SelectedItem == null) { return; //ItemSelected is called on deselection, //which results in SelectedItem being set to null } var vSelUser = (Employee)e.SelectedItem; Navigation.PushAsync(new ShowEmplyee(vSelUser)); } public void OnNewClicked(object sender, EventArgs args) { Navigation.PushAsync(new AddEmployee()); }
10. Add Employee Page
Design
<ContentView.Content> <TableView Intent="Settings" BackgroundColor="White"> <TableRoot> <TableSection Title="Add New Employee"> <EntryCell x:Name="txtEmpName" Label="Employee Name" Keyboard="Text" /> <EntryCell x:Name="txtDesign" Label="Designation" Keyboard="Text" /> <EntryCell x:Name="txtDepartment" Label="Department" Keyboard="Text" /> <EntryCell x:Name="txtQualification" Label="Qualification" Keyboard="Text" /> <ViewCell> <ContentView Padding="0,0"> <ContentView.Padding> <OnPlatform x:TypeArguments="Thickness" iOS="10,0" WinPhone="0,15,0,0" /> </ContentView.Padding> <ContentView.Content> <Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked" /> </ContentView.Content> </ContentView> </ViewCell> </TableSection> </TableRoot> </TableView> </ContentView.Content>
Code
public AddEmployee() { InitializeComponent(); } public void OnSaveClicked(object sender, EventArgs args) { var vEmployee = new Employee() { EmpName = txtEmpName.Text, Department = txtDepartment.Text, Designation = txtDesign.Text, Qualification = txtQualification.Text }; App.DAUtil.SaveEmployee(vEmployee); Navigation.PushAsync(new ManageEmployee()); }
11. View Employee Page
Design
<ContentView.Content> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="10"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="10"/> </Grid.ColumnDefinitions> <Label Grid.Row ="0" Grid.Column="0" Grid.ColumnSpan="2" Text="Employee Details" /> <Label Grid.Row ="1" Grid.Column="1" Text="Name" /> <Label Grid.Row="1" Grid.Column="2" Text ="{Binding EmpName}" /> <Label Grid.Row ="2" Grid.Column="1" Text="Designation" /> <Label Grid.Row="2" Grid.Column="2" Text ="{Binding Designation}"/> <Label Grid.Row ="3" Grid.Column="1" Text="Department" /> <Label Grid.Row="3" Grid.Column="2" Text ="{Binding Department}"/> <Label Grid.Row ="4" Grid.Column="1" Text="Qualification" /> <Label Grid.Row="4" Grid.Column="2" Text ="{Binding Qualification}" /> <Button Grid.Row ="5" Grid.Column="1" Text="Edit Details" Clicked="OnEditClicked" /> <Button Grid.Row="5" Grid.Column="2" Text="Delete" Clicked="OnDeleteClicked" /> </Grid> </ContentView.Content>
Code Employee mSelEmployee; public ShowEmplyee(Employee aSelectedEmp) { InitializeComponent(); mSelEmployee = aSelectedEmp; BindingContext = mSelEmployee; } public void OnEditClicked(object sender, EventArgs args) { // Navigation.PushAsync(new EditEmployee(mSelEmployee)); } public async void OnDeleteClicked(object sender, EventArgs args) { bool accepted = await DisplayAlert("Confirm", "Are you Sure ?", "Yes", "No"); if (accepted) { App.DAUtil.DeleteEmployee(mSelEmployee); } await Navigation.PushAsync(new ManageEmployee()); }
12. Edit Employee Page
Design
<ContentView.Content> <TableView Intent="Settings" BackgroundColor="White"> <TableRoot> <TableSection Title="Edit Employee"> <EntryCell x:Name="txtEmpName" Label="Employee Name" Text ="{Binding EmpName}" Keyboard="Text" /> <EntryCell x:Name="txtDesign" Label="Designation" Text ="{Binding Designation}" Keyboard="Text" /> <EntryCell x:Name="txtDepartment" Label="Department" Text ="{Binding Department}" Keyboard="Text" /> <EntryCell x:Name="txtQualification" Label="Qualification" Text ="{Binding Qualification}" Keyboard="Text" /> <ViewCell> <ContentView Padding="0,0"> <ContentView.Padding> <OnPlatform x:TypeArguments="Thickness" iOS="10,0" WinPhone="0,15,0,0" /> </ContentView.Padding> <ContentView.Content> <Button BackgroundColor="#fd6d6d" Text="Save" TextColor="White" Clicked="OnSaveClicked" /> </ContentView.Content> </ContentView> </ViewCell> </TableSection> </TableRoot> </TableView> </ContentView.Content>
Code
Employee mSelEmployee; public EditEmployee(Employee aSelectedEmp) { InitializeComponent(); mSelEmployee = aSelectedEmp; BindingContext = mSelEmployee; } public void OnSaveClicked(object sender, EventArgs args) { mSelEmployee.EmpName = txtEmpName.Text; mSelEmployee.Department = txtDepartment.Text; mSelEmployee.Designation = txtDesign.Text; mSelEmployee.Qualification = txtQualification.Text; App.DAUtil.EditEmployee(mSelEmployee); Navigation.PushAsync(new ManageEmployee()); }
Xamarin | How to set application published name and version
Xamarin | How to set application published name and version
Set Application name
1. Open "AndroidManifest.xml" file from ProjectName\ProjectName.Droid\Properties folder
2. set application name which you want in blow property,
<application android:label="MyApp"></application>
Set Application Version
2. Set version number which you want,
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Xamarin : Splash Screen
Xamarin : Splash Screen
1. Create images for respective resolutions and store it in the same folder in Resources folder of "ProjectName.Droid" project
MDPI = 320 × 480 dp = 320x480px (The Default x1)
XHDPI = 2 x MDPI = 640x960px
XXHDPI = 3 x MDPI = 960x1440px
XXXHDPI = 4 x MDPI = 1280x1920px
XHDPI = 2 x MDPI = 640x960px
XXHDPI = 3 x MDPI = 960x1440px
XXXHDPI = 4 x MDPI = 1280x1920px
2. Create new activity name "SplashActivity.cs" in Droid project
[Activity(Theme = "@style/Theme.Splash",
MainLauncher = true,
NoHistory = true)]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
System.Threading.Thread.Sleep(3000);
StartActivity(typeof(MainActivity));
}
}
3. Open "MainActivity.cs" File and set MainLauncher = false
4. Set styles, open styles.xml from Resources -> Values folder
<style name="Theme.Splash" parent="MainTheme.Base">
<item name="android:background">@drawable/splashscreen</item>
<item name="windowNoTitle">True</item>
</style>
<style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar"> </style>
5. Run the application and see the splash screen
Subscribe to:
Posts (Atom)
-
Enable CORS on Web API project Error: Access to XMLHttpRequest at 'http://local-corsapi.com/api/demo' from origin ...
-
Insert - Update SQL Database using Powershell Script Here is example of SQL Server database insert and update transaction using Powershel...
-
Azure Service Bus - Send & Receive Message - Topic in .Net Core I have seen many examples to send and receive message of Azure Servi...