title: Getting application context for getInstance function of database class (android kotlin)
body: <p>I am writing an android application following the Android Architectural Components design.</p>
  <p>This is the database class:</p>
  <pre><code>@Database(entities = [Authentication::class],version = 1, exportSchema = false)
  abstract class AuthDB: RoomDatabase(){
      abstract val authenticationDao :AuthenticationAccessObject
  
      companion object{
          @Volatile
          private var INSTANCE: AuthDB? = null
  
          fun getInstance(context: Context): AuthDB {
              synchronized(this){
                  var instance = INSTANCE
                  if(instance == null){
                      instance = Room.databaseBuilder(
                          context.applicationContext,
                          AuthDB::class.java,
                          &quot;authentication_database&quot;
                      )
                          .fallbackToDestructiveMigration()
                          .build()
                      INSTANCE = instance
                  }
                  return instance
                              }
          }
      }
  
  }
  </code></pre>
  <p>This is the Repository class:</p>
  <pre><code>class Repository2() {
  
  private val database: AuthDB = AuthDB.getInstance(context = getContext())
  private val daoA = database.authenticationDao
  //Function to register a new user to system
      fun insertAuth(userData: Any){
          if (userData is Authentication){
              daoA.insertAuth(userData)
          } else {
              throw IllegalArgumentException()
          }
      }
  </code></pre>
  <p>My target is that when I write the ViewModel, I want to create instance of Repository2 and call functions for example as follows:</p>
  <pre><code>var repo = Repository2()
  repo.insertAuth(authenticationObject)
  </code></pre>
  <p>I am having problem giving context to getInstance in the Repository. The context should be such that when I instantiate the repository, it should automatically get the application context and instantiate the AuthDB database.</p>
  <p>Until now,</p>
  <ol>
  <li><p>I have tried to create Application class that extends Application and tried to get application context from there as suggested in another stackoverflow solution</p>
  </li>
  <li><p>Instantiated database with following code and failed:</p>
  <p>private val database: AuthDB = AuthDB.getInstance(context = getContext())</p>
  </li>
  <li><p>Instantiated database with following code and failed:</p>
  <p>private val database: AuthDB = AuthDB.getInstance(Application.getApplicationContext())</p>
  </li>
  </ol>
  <p>I have been trying for about two days now and nothing is working, I believe I am missing a major concept here. I hope someone can nudge me in the right direction?</p>
  <p>Kind regards,
  Salik</p>