如何使用Kotlin在片段内部访问活动中的SQLite DB?

时间:2019-06-28 14:35:54

标签: android android-fragments kotlin

我创建了一个带有表和MainActivity.kt中条目的SQLite数据库。我有一个片段AllUsersFragment.kt,上面有一个列表。每当单击列表中的项目时,该片段都应运行查询以从MainActivity.kt中的数据库中获取/编辑某些内容。

我试图在MainActivity.kt中创建一个可以从片段中调用的函数,但是事实证明,在onCreate()的{​​{1}}之外甚至无法访问该数据库。我正在使用Kotlin语言。 我在这里找到了Java的答案,但没有找到Kotlin的答案。

MainActivity.kt

MainActivity.kt

AllUsersFragment.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            val myDatabase = this.openOrCreateDatabase("CreditsDB", Context.MODE_PRIVATE, null)

//            myDatabase.execSQL("CREATE TABLE IF NOT EXISTS credits (serial INT(3) PRIMARY KEY, name VARCHAR(256), credits INT(10))")

//            myDatabase.execSQL("INSERT INTO credits (serial, name, credits) VALUES (1, 'Andrew Jackson', 10000)")
//            myDatabase.execSQL("INSERT INTO credits (serial, name, credits) VALUES (2, 'Barry Alan', 20000)")
//            myDatabase.execSQL("INSERT INTO credits (serial, name, credits) VALUES (3, 'Caitlyn Snow', 15000)")
//            myDatabase.execSQL("INSERT INTO credits (serial, name, credits) VALUES (4, 'Drake Ramoray', 8000)")

        }
        catch(e: Exception)
        {
            e.printStackTrace()
        }

    //Initial Fragment during app start
        title = resources.getString(R.string.allusers)
        loadFragment(AllUsersFragment())

    //BOTTOM NAVIGATION BAR
        navigationView.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.navigation_allusers -> {
                    title = resources.getString(R.string.allusers)
                    loadFragment(AllUsersFragment())
                    return@setOnNavigationItemSelectedListener true
                }

                R.id.navigation_transfer -> {
                //Omitted unimportant code here
                }

                R.id.navigation_logs -> {
                //Omitted unimportant code here     
                }

            }

            false
        }
    }


    fun loadFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }
}

请在上方class AllUsersFragment : Fragment(){ private lateinit var listView:ListView override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val rootView = inflater.inflate(R.layout.fragment_allusers, container, false) val details = UserDetailsFragment() val bundle = Bundle() listView = rootView.findViewById(R.id.usersList) val userNames = arrayOf( "Andrew Jackson", "Barry Alan", "Caitlyn Snow", "Drake Ramoray", ) val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, userNames) listView.adapter = adapter listView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l -> val userName = userNames[i] bundle.putString("str", userName) bundle.putInt("int", i) details.arguments = bundle //========================================================= //expected operation here: //var query = "SELECT credits (column name) FROM credits (table name) WHERE serial = (id+1)" //var creditsAmt : Int = myDatabase.execSQL(query) (SOMEHOW THIS SHOULD ACCESS DATABASE IN MainActivity.kt) //========================================================= val transaction = fragmentManager!!.beginTransaction() transaction.replace(R.id.container, details) transaction.addToBackStack(null) transaction.commit() } return rootView } } 中找到带注释的部分,其中描述了我的实际需求。

1 个答案:

答案 0 :(得分:0)

您这样做:

   class MainActivity : AppCompatActivity() {

        val myDatabase : YourDatabaseClassName? = null

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            try {
                myDatabase = this.openOrCreateDatabase("CreditsDB", Context.MODE_PRIVATE, null)


            }
            catch(e: Exception)
            {
                e.printStackTrace()
            }

在片段中,您可以像这样使用数据库实例:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val rootView = inflater.inflate(R.layout.fragment_allusers, container, false)

   .......

   // here how you call your database instance
    var query = "SELECT credits (column name) FROM credits (table name) WHERE serial = (id+1)"
    var creditsAmt : Int = (activity as MainActivity).myDatabase!!.execSQL(query)

}