"You must call Xamarin.forms.init() prior to using it" - Problem trying to access sqlite data

Asked

Viewed 324 times

1

Hello,

I’m a beginner in mobile programming and I’m committed to a project PCL Xamarin with Xamarin.Forms. The application uses alarms and for this I use dependency injection to access the native classes that take care of notifications. No Android use the class AlarmManeger which naturally has the logs deleted when the device is turned off. To restore the alarms I created a class in the project Android who inherits from BroadcastReceiver and fires on action ActionBootCompleted and would like to access the database SQLite from the project PCL. But when referencing the connection I get the following exception:

Exception após a inicialização do dispositivo.

"Bootreceiver" class (project . Droid):

namespace NutriTime.Droid.Notification
{
  [BroadcastReceiver]
  [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted },
      Categories = new[] { Android.Content.Intent.CategoryDefault })]
  public class BootReceiver : BroadcastReceiver
  {
      public override void OnReceive(Context context, Intent intent)
      {           
          try
          {
              //A linha abaixo gera a Exception
              NutriTime.Data.RefeicaoRepository dados = new NutriTime.Data.RefeicaoRepository(NutriTime.App.DataBase); 

              //TODO:Manipulação dos dados

              Toast.MakeText(context, "Ok", ToastLength.Long).Show();
          }
          catch (Exception e)
          {
              Toast.MakeText(context, e.ToString(), ToastLength.Long).Show();
          }
      }        
  }
}

Sqlite configuration (project . Droid):

[assembly: Dependency(typeof(NutriTime.Droid.Data.SQLite_Android))]

namespace NutriTime.Droid.Data
{
  public class SQLite_Android : ISQLite
  {
     private string _diretorioDB;
     public string DiretorioDB
     {
         get
         {
             if (string.IsNullOrEmpty(_diretorioDB))
             {
                 _diretorioDB = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
             }
             return _diretorioDB;
         }
     }
     private SQLite.Net.Interop.ISQLitePlatform _plataforma;
     public ISQLitePlatform Plataforma
     {
        get
        {
            if (_plataforma == null)
            {
                _plataforma = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
            }
            return _plataforma;
      }
    }
  }
}

Sqlite Abstraction Interface (Portable Design):

namespace NutriTime.Interfaces
{
  public interface ISQLite
  {
      string DiretorioDB { get; }
      ISQLitePlatform Plataforma { get; }
  }
}

Class responsible for creating the database (Portable project):

namespace NutriTime.Data
{
  public class DBConnection
  {
      private SQLiteConnection _con;
      public DBConnection()
      {
         var config = DependencyService.Get<ISQLite>();
         _con = new SQLite.Net.SQLiteConnection(config.Plataforma, System.IO.Path.Combine(config.DiretorioDB, "nutritimedb.db3"));

         _con.CreateTable<PacienteModel>();
         _con.CreateTable<RefeicaoModel>();
         _con.CreateTable<AlimentoModel>();
         _con.CreateTable<ItemModel>();

       }
       public SQLiteConnection GetConnection()
       {
          return _con;
       }
   }
}

What is the most suitable way to access Sqlite data within the specific Android project?

  • The code shown does not help identify the problem, show the configuration code of the SQLite within the project Android. For more details see in this question: http://answall.com/questions/126353/xamarin-dependencyservice-null @Dantas-j

  • @rubStackOverflow you are talking about the implementation of Sqlite in the android project?

  • Exactly @Dantas-j

  • Also put the code where you are instantiating SQLite_Android . When you are debugandowhere exactly the error occurs?

  • @rubStackOverflow the error occurs in the Bootreceiver class that runs automatically when the device boots. Error line specified (line 13).

  • Later I will compare with my code and try to help. @Dantas-j

  • Does this code run when the phone is turned on correctly? Running a simple test (without needing to restart) does the connection to the bank work? @Dantas-j

  • 1

    @rubStackOverflow The connection to the database works perfectly in the classes of data manipulation (the Models) in the Portable project. In the Bootreceiver class I can’t run the code without restarting the device :/

  • Correcting: in the classes of data manipulation (the Viewmodels)

Show 4 more comments

1 answer

1

After more research I realized where I was going wrong.

In the Bootreceiver class, where you have

//A linha abaixo gera a Exception
          NutriTime.Data.RefeicaoRepository dados = new NutriTime.Data.RefeicaoRepository(NutriTime.App.DataBase);

Replaced by

            SQLite.Net.Interop.ISQLitePlatform plataforma = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
            string diretorioDB = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            using (SQLiteConnection _con = new SQLite.Net.SQLiteConnection(plataforma, System.IO.Path.Combine(diretorioDB, "nutritimedb.db3")))
            {
               //Manipulação de dados                      
            }

Basically, from what I understood, I was trying to access the database through the classes of access to data present in the PCL project (including the App class) that require the initialization of Xamarin.Forms.

Anyone who feels comfortable to explain better or complement/correct my answer, feel free. Thank you.

This is where I realized my mistake: https://stackoverflow.com/questions/18715613/use-a-local-database-in-xamarin

Browser other questions tagged

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