Alan Huang Alan Huang - 2 years ago 170
Android Question

Xamarin Forms - Working with SQLite

I have been trying to follow this video to learn working with SQLite in Xamarin Forms and I am stuck

https://www.youtube.com/watch?v=FVH-9zjRP9M

project.Droid

class LocalDatabaseHelper : Classes.ILocalDatabaseHelper
{
public string GetLocalFilePath(string fileName)
{
string docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");

if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
return Path.Combine(libFolder, fileName);
}
}


project (pcl)

public static Classes.TaskReminder.TaskReminderDatabaseOperation Database
{
get
{
if (database == null)
{
string LocalFilePath = "";
if(Device.OS==TargetPlatform.Android)
{
LocalFilePath = DependencyService.Get<Classes.ILocalDatabaseHelper>().GetLocalFilePath("TaskReminder.db3");
}
database = new Classes.TaskReminder.TaskReminderDatabaseOperation(LocalFilePath);
}
return database;
}
}

public interface ILocalDatabaseHelper
{
string GetLocalFilePath(string fileName);
}


And it is giving me Unhandled exception when executing

LocalFilePath = DependencyService.Get<Classes.ILocalDatabaseHelper>().GetLocalFilePath("TaskReminder.db3");


please help. thanks in advance.

NOTE (more information):

project (PCL)

public class TaskReminderDatabaseOperation
{
readonly SQLiteAsyncConnection database;
public TaskReminderDatabaseOperation(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<TaskReminder>().Wait();
}

public Task<List<TaskReminder>> GetTaskRemindersAsync()
{
return database.Table<TaskReminder>().ToListAsync();
}

public Task<TaskReminder> GetTaskReminder(DateTime datetime)
{
return database.Table<TaskReminder>().Where(i => i.ReminderDateTime == datetime).FirstOrDefaultAsync();
}

public Task<int> SaveTaskReminder(TaskReminder taskReminder)
{
if (taskReminder.Id == 0)
{
return database.InsertAsync(taskReminder);
}
else
{
return database.UpdateAsync(taskReminder);
}
}

public Task<int> DeleteTaskReminder(TaskReminder taskReminder)
{
return database.DeleteAsync(taskReminder);
}
}

Answer Source

Look closely at the video, around 29 minutes and 10 seconds. You will see that he adds a attribute to the project class. This registers the dependency with the Dependency Service in Xamarin.Forms.

You probably forgot to do that, that is why you will get a NullReferenceException when you try to resolve the implementation of the interface.

Please look into the workings of the Dependency Service to understand how these kinds of things work and resolve these errors for yourself, instead of just following the video.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download