Photo by pxhere.com

Copy assets in a Xamarin.Android application

Sometimes when you are starting an application you do not have all the data ready, but you need to start to develop your application.

Posted by Damien Aicheh on 04/14/2018 · 2 mins

Sometimes when you are starting an application you do not have all the data ready, but you need to start to develop your application.

In this tutorial we are in the situation where we need to use data from a database that will be populated by the user when he will use the application. So for development purpose we want to embed it in the application.

To make the database accessible inside your application we need to deploy it, in the current folder of the application to use it.

First of all, in you Xamarin.Android project you will need to add your database in the Assets folder. Mine is called database.db3. Then in your IDE, right click on it and choose Properties and make sure the Build Action is set on AndroidAsset. Without this option set correctly the following will not working.

Now in your Xamarin.Android project in an Activity add this Task method :

public async Task DeployDatabaseFromAssetsAsync()
{
    var databaseName = "database.db3";
    
    // Android application default folder.
    var appFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    var dbFile = Path.Combine(appFolder, databaseName);
    
    // Check if the file already exists.
    if (!File.Exists(dbFile))
    {
        using(FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write))
        {
            // Assets is comming from the current context.
            await Assets.Open(databaseName).CopyToAsync(writeStream);
        }
    }
}

You can call this Task at the beginning of your application, and your database will be deployed. The best to do is to create a service that is implemented for each platform and call this method by using dependency injection.

You will find an example code in this Github repository.

Happy coding!

You liked this tutorial? Leave a star in the associated Github repository!

Do not hesitate to follow me on to not miss my next tutorial!