Null reference exception when sqlite table is empty

Hello guys. The issue that am having is that am having a null reference exception that is object not set to an instance of an object whenever I run my program. What I want to achieve is to sum the row values of sqlite table and store it in an int variable. I was able to do that if and only if the table is not empty but if the table is empty, it gives me a null reference exception. So how can I catch this exception

Answers

  • matrixlukanmatrixlukan Member ✭✭

    Can you be more clear.
    Can you show the code.

  • JarvanJarvan Member, Xamarin Team Xamurai

    Check if the count of table is empty. If not, execute the command.

    var count = await db.ExecuteScalarAsync("select count(*) from Stock",null);
    if(count!=0)
    {
        //execute the code
    }
    
  • ousous Member ✭✭
    Jarvan I think I did something similar to this but I will try it when I reach home. Thank you
  • ousous Member ✭✭
    Matrixlukan am not with my computer right but will do that whem am home.
  • ousous Member ✭✭

    Jarvan this is my code but am still getting the error

    public async Task SumItemAsync_()
    {
    var data = await db.ExecuteScalarAsync("SELECT SUM(Amount) FROM Spent",null);
    if (data != 0)
    {
    return data;
    }
    else
    {
    return 0;
    }
    }

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited August 20

    I was able to do that if and only if the table is not empty but if the table is empty, it gives me a null reference exception.

    Try to set the 'Amount' column to NOT NULL.

    Or check if data is not null.

    var data = await db.ExecuteScalarAsync("SELECT SUM(Amount) FROM Spent",null);
    if (data != null)
    {
        return data;
    }
    
Sign In or Register to comment.