Deployed Android App not working with database

91 views Asked by At

I have a strange situation where I developed an Android App for a Samsung Tablet that is not working as intended. The User registration step (first step of the app) is not working and is generating a null error.
During the development phase, the MAUI Blazor Hybrid App was thoroughly tested on Windows and Samsung tablets; all emulators ran successfully as well. However, after deploying (a full install of the .apk file) the App on the same development Tablet, the App launched successfully but the user registration failed with a Null error. It seems as though the database is not getting found (created) as it should or did during development.

I am registering the database with the following path:

    public class SQLiteDatabase:DbContext
    {
        public static string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ActivityData.db3");
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {          
            optionsBuilder.UseSqlite($"Filename={dbPath}");
        }
    }

// and properly setup the injection service in the MauiProgram.cs:
 builder.Services.AddSingleton<SQLiteDatabase>();

Is there a special way to setup the database for Android? What else can I do to get this working?

1

There are 1 answers

3
Guangyu Bai - MSFT On

Maui provide the local database for developers to use. You can check this document to use SQLite NuGet package.

First, you need to add the SQLite NuGet package and config the data. The sample project includes a Constants.cs file that provides common configuration data.

Second, you need to create a database access class.

public class TodoItemDatabase
{
    SQLiteAsyncConnection Database;

    public TodoItemDatabase()
    {
    }

    async Task Init()
    {
        if (Database is not null)
            return;

        Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
        var result = await Database.CreateTableAsync<TodoItem>();
    }
    ...
}

Last, you can use the methods below to manipulate the data.

 public async Task<TodoItem> GetItemAsync(int id)
    {
        await Init();
        return await Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
    }

    public async Task<int> SaveItemAsync(TodoItem item)
    {
        await Init();
        if (item.ID != 0)
            return await Database.UpdateAsync(item);
        else
            return await Database.InsertAsync(item);
    }

    public async Task<int> DeleteItemAsync(TodoItem item)
    {
        await Init();
        return await Database.DeleteAsync(item);
    }