0

I would like to create a singleton to access some functions, but when I import it, It doesn't find the class to import:
enter image description here

Class with singleton:
DBHandler.kt

    package com.xxxxx.GMP_app_android.DBManagement

    import android.database.sqlite.SQLiteDatabase
    import android.database.sqlite.SQLiteOpenHelper
    import android.content.Context
    import android.content.ContentValues
    import android.content.ContentResolver
    import com.NewTelApps.GMP_app_android.DBLocal
    import com.NewTelApps.GMP_app_android.DBServer
    import android.support.v7.app.AppCompatActivity
    import android.os.Bundle
    import android.view.View

    class DBHandler : AppCompatActivity() {
        var sharedManager: DBHandler? = null

        fun createInstance(): DBHandler {
            if (sharedManager == null) {
                sharedManager = DBHandler()
            }
            return sharedManager!!
        }

        fun getInstance(): DBHandler? {
            if (sharedManager == null) createInstance()
            return sharedManager
        }


        fun methodToSelectData(strQuery: String, dataBase: String)/*, completion: @escaping (_ result:*/
        {
    /*        val dbLocal = DBLocal(this, null, null, 1)
            dbLocal.methodToSelectData(strQuery)*/
        }

        fun methodToInsertUpdateDeleteData(strQuery: String)/*, completion: @escaping (_ result: Bool) -> Void)*/
        {

        }
    }

Usage in another class: Impossible to access to getInstance()

DBHandler.getInstance().methodToSelectData("SELECT * FROM TABLE")

Any ideas? Thanks in advance.

ΩlostA
  • 2,501
  • 5
  • 27
  • 63
  • If this is a Singleton, then it shouldn't expect AppCompatActivity. If this is a Singleton, I don't know why it doesn't just use `object` from Kotlin, considering this is Kotlin code. – EpicPandaForce Mar 07 '19 at 09:45
  • @EpicPandaForce I tried some code, I think I let it by mistake. – ΩlostA Mar 07 '19 at 09:50

1 Answers1

3

That's not how that works in Kotlin. In your code, getInstance() is a regular method that needs an instance of your DBHandler class. So that method is not static and cannot be called like you're trying to do.

object is the default way of doing singletons in Kotlin. But if you want something more powerful and need an instance, have a look at those: Singleton class in Kotlin

Basically you return an instance of the class from a companion object.

BTW, why does your DBHandler extends AppCompatActivity?

shkschneider
  • 17,833
  • 13
  • 59
  • 112