Search code examples
c#xamarinxamarin.androidsqlite-netsqlite-net-extensions

Xamarin Sqlite-Net Insert (Object reference not set to an instance of an object)


I have a very strange problem that I can't figure out. I cannot insert a new item into my Sqlite DB. I keep receiving this error:-

System.NullReferenceException: Object reference not set to an instance of an object.

I literally have no idea why and have the exact same code working and saving other tables within the application.

Here is my code:-

User.cs

public class User
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Name { get; set; }
    public string EmailAddress { get; set; }

    public User()
    {
        this.Name = " ";
        this.EmailAddress = " ";
    }
}

UserManager.cs

public class UserManager 
{
    UserRepository repository; 

    public UserManager(SQLiteConnection conn)
    {
        repository = new UserRepository (conn);
    }

    public User GetDriver(int id)
    {
        return repository.GetDriver(id);
    }

    public IList<User> GetDrivers()
    {
        return new List<User>(repository.GetDrivers());
    }

    public int SaveDriver(User item)
    {
        return repository.SaveDriver(item);
    }

    public int DeleteDriver(int id)
    {
        return repository.DeleteDriver(id);
    }
}

UserRepository.cs

public class UserRepository
{
    UserDatabase db = null;

    public UserRepository(SQLiteConnection conn)
    {
        db = new UserDatabase(conn);
    }

    public User GetDriver(int id)
    {
        return db.GetDriverItem(id);
    }

    public IEnumerable<User> GetDrivers()
    {
        return db.GetAllDriverItems();
    }

    public int SaveDriver(User item)
    {
        return db.SaveDriverItem(item);
    }

    public int DeleteDriver(int id)
    {
        return db.DeleteDriverItem(id);
    }
}

UserDatabase.cs

public class UserDatabase
{
    static object locker = new object();
    public SQLiteConnection database;
    public string path;

    public UserDatabase(SQLiteConnection conn)
    {
        database = conn;
        database.CreateTable<User>();
    }

    public IEnumerable<User> GetAllDriverItems () {
        lock (locker) {
            return (from i in database.Table<User>() select i).ToList();
        }
    }

    public User GetDriverItem (int id) 
    {
        lock (locker) {
            return database.Table<User>().FirstOrDefault(x => x.ID == id);
        }
    }

    public int SaveDriverItem (User item) 
    {
        lock (locker) {
            if (item.ID != 0) {
                database.Update(item);
                return item.ID;
            } else {
                return database.Insert(item);
            }
        }
    }

    public int DeleteDriverItem(int id) 
    {
        lock (locker) {
            return database.Delete<User>(id);
        }
    }
}

Application.cs (In Android)

public class UserApp : Application
{
    public static UserApp Current { get; private set; }

    public UserManager UserManager { get; set; }

    SQLiteConnection conn;

    public UserApp(IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer)
        : base(handle, transfer)
    {
        Current = this;
    }

    public override void OnCreate()
    {
        base.OnCreate();

        var sqliteFilename = "UserItemDB.db3";
        string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        var path = Path.Combine(libraryPath, sqliteFilename);
        conn = new SQLiteConnection(new SQLite.Net.Platform.Generic.SQLitePlatformGeneric(), path);

        UserManager = new UserManager(conn);

        User testUser= new User();
        testUser.Name = "Dave";
        testUser.EmailAddress = "[email protected]";
        UserApp.Current.UserManager.SaveDriver(testUser);
    }

Here is my stack trace:-

System.NullReferenceException: Object reference not set to an instance of an object.
08-09 17:07:32.423 E/mono    (31670):   at     System.Reflection.MonoProperty.GetValue (System.Object obj, System.Object[]     index) [0x00031] in <filename unknown>:0 
08-09 17:07:32.423 E/mono    (31670):   at     SQLite.Net.TableMapping+Column.GetValue (System.Object obj) [0x00000] in     <filename unknown>:0 
08-09 17:07:32.423 E/mono    (31670):   at     SQLite.Net.SQLiteConnection.Insert (System.Object obj, System.String extra,     System.Type objType) [0x00098] in <filename unknown>:0 
08-09 17:07:32.423 E/mono    (31670):   at     SQLite.Net.SQLiteConnection.Insert (System.Object obj) [0x00012] in <filename     unknown>:0 
08-09 17:07:32.423 E/mono    (31670):   at     Project.DataLayer.UserDatabase.SaveDriverItem (Project.BusinessLayer.Models.User     item) [0x00038] in     C:\Users\phill\Desktop\Work\ProjectTEST\Project\Project.Shared\DataLayer\UserDat    abase.cs:42 
08-09 17:07:32.423 E/mono    (31670):   at     Project.DataAccessLayer.UserRepository.SaveDriver     (Project.BusinessLayer.Models.User item) [0x00001] in     C:\Users\phill\Desktop\Work\ProjectTEST\Project\Project.Shared\DataAccessLayer\U    serRepository.cs:30 
08-09 17:07:32.423 E/mono    (31670):   at     Project.BusinessLayer.Managers.UserManager.SaveDriver     (Project.BusinessLayer.Models.User item) [0x00001] in     C:\Users\phill\Desktop\Work\ProjectTEST\Project\Project.Shared\BusinessLayer\Man    agers\UserManager.cs:33 
08-09 17:07:32.423 E/mono    (31670):   at Project.Droid.UserApp+    <getDriverDetails>d__16.MoveNext () [0x000e2] in     C:\Users\phill\Desktop\Work\ProjectTEST\Project\Project.Droid\Application.cs:75 

Solution

  • Solved - After a long headache I finally figured out the issue.

    Okay so the NullObject refers to the database file itself. The structure of the DB could not be changed and my application couldn't create a new DB due to some settings in Xamarin. Not 100% sure which of these was the exact answer but my project finally worked shortly after...

    In VS go to Tools > Options > Xamarin > Android > Tick "Preserve Application Data"

    I think this is the main issue ^^. I also had checked/unchecked others too.

    Project > Project.Properties > Android Options > Tick Shared Runtime & Fast Deployment And next tab Linker = None.

    Not sure which of the above solved my issue but it's running perfectly