Object reference not set to an instance of an object

2

I'm learning to do App using Xamarin 2017 , and when I try to connect to the database I created via SQLite , the application has 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>();
    
asked by anonymous 29.09.2017 / 23:12

1 answer

0

The goal of DependencyService is to facilitate the creation of APP that access platform-specific APIs (Android, IOS, Windows Mobile, etc.).

If the study you are doing does not require this portability, you can directly instantiate the object of the class that implements IDatabaseConnection without using DependencyService .

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

Now, if you're going to use DependencyService , you'll need to implement 3 things in your project:

1) Set interface

public interface IDatabaseConnection
{
    MinhaClasseConexao ConexaoDatabase(); 
}

2) Create the class that implements 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
   }
}

See: Introduction to DependencyService

For the description of your problem, you should have taken the first step but did not implement the other two.

    
30.09.2017 / 19:50