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



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

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

MainActivity.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()
}
}

AllUsersFragment.kt

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
}
}

请在上面的AllUsersFragment.kt中找到注释部分,其中描述了我确切需要的内容。

你这样做:

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)
}

最新更新