Object Reference not set to an instance of an Object

Asked

Viewed 918 times

2

I’m learning to do App using the Xamarin 2017, and when I try to connect to the database I created via SQLite, the application shows this error:

Object Reference not set to an instance of an Object.

How could I fix this?

The error occurs at this point:

public UsuarioDataAccess()
{
    database = DependencyService
            .Get<IDatabaseConnection>()
            .ConexaoDatabase();
    database.CreateTable<Usuario>();
  • is the variable database where this error occurs?

  • Exactly. I don’t know what to do...

  • You have to check with a debug because that line DependencyService .Get<IDatabaseConnection>().ConexaoDatabase(); is not returning a bank connection, already tried to do this ... ???

  • 1

    He only has a problem when I do this.. and that’s the message that appears when I debug

  • You created the class that implements the Idatabaseconnection interface?

1 answer

0

The objective of DependencyService is to facilitate the creation of APP that accesses specific API’s of each platform (Android, IOS, Windows Mobile, etc).

If the study you are doing does not require this portability, you can instantiate the object of the implementing class directly IDatabaseConnection unused DependencyService.

database = (new CLASSE_QUE_IMPLEMENTA_IDatabaseConnection()).ConexaoDatabase();
database.CreateTable<Usuario>();

Now, if you’re gonna use DependencyService, will need to implement 3 things in your project:

1) Define the interface

public interface IDatabaseConnection
{
    MinhaClasseConexao ConexaoDatabase(); 
}

2) Create the class that implements the interface

public class DatabaseConnectionImplementacao : IDatabaseConnection
{ 
   // implementar código da classe
} 

3) Register the class that implements the interface;

//registrar a classe usando um atributo do namespace da classe 
[assembly: Xamarin.Forms.Dependency (typeof (DatabaseConnectionImplementacao ))]
namespace MeuApp.Android 
{
   public class DatabaseConnectionImplementacao : IDatabaseConnection
   { 
      // implementar código da classe
   }
}

Behold: Introduction to Dependencyservice

By the description of your problem, you must have made the first step but not implemented the other two.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.