kotlin 上的微调器出现空指针异常

问题描述 投票:0回答:1

我在使用 onItemSelectedListener 实现 Spinner 时遇到了 Kotlin Android 代码问题。我尝试使用从 SQLite 数据库检索的数据填充 Spinner,但在尝试在 onItemSelected 方法中访问 Spinner 时不断遇到 NullPointerException。

这是我的代码片段:

var spinner = findViewById<Spinner>(R.id.spinner)
var ls = findViewById<ListView>(R.id.ls)
var arr = emptyArray<String>()
val cursor: Cursor = databaseHelper.getcountries()
if (cursor.count == 0) {
    Toast.makeText(this, "Nothing to display", Toast.LENGTH_SHORT).show()
}
while (cursor.moveToNext()) {
    val countrytemp = cursor.getString(0)
    arr += countrytemp
}
var adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, arr)
spinner.adapter = adapter
var selectedItem = ""
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(
        parent: AdapterView<*>?,
        view: View?,
        position: Int,
        id: Long
    ) {
        // NullPointerException occurs here
        selectedItem = parent?.getItemAtPosition(position).toString()
        Toast.makeText(this@SecondActivity, selectedItem, Toast.LENGTH_SHORT).show()
    }
}


我认为 CRUD 操作一定存在一些问题,如果有人能给我一个纲要,我会很高兴

android kotlin spinner
1个回答
0
投票

这就是使用 SQLite 在 Kotlin 中设置 CRUD 操作所需执行的所有操作。在您的代码中,您没有添加没有选择任何内容的条件,这就是您面临此问题的原因

数据库

Go to AndroidManifest.xml

add these permissions -

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

below <manifest> tag and above <application> tag

like here 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Androidstudio"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Make New Class DatabaseHelper and add the code below - 

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {

    companion object {
        private const val DATABASE_VERSION = 1
        private const val DATABASE_NAME = "StudentManager.db"

        // Table name and columns
        private const val TABLE_NAME = "students"
        private const val COLUMN_ROLL_NUMBER = "roll_number"
        private const val COLUMN_NAME = "name"
        private const val COLUMN_MARKS = "marks"
    }

    override fun onCreate(db: SQLiteDatabase?) {
        val createTableQuery = "CREATE TABLE $TABLE_NAME (" +
                "$COLUMN_ROLL_NUMBER TEXT PRIMARY KEY," +
                "$COLUMN_NAME TEXT," +
                "$COLUMN_MARKS INTEGER)"
        db?.execSQL(createTableQuery)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
        onCreate(db)
    }

    fun addStudent(rollNumber: String, name: String, marks: Int): Boolean {
        val db = this.writableDatabase
        val contentValues = ContentValues()
        contentValues.put(COLUMN_ROLL_NUMBER, rollNumber)
        contentValues.put(COLUMN_NAME, name)
        contentValues.put(COLUMN_MARKS, marks)
        val result = db.insert(TABLE_NAME, null, contentValues)
        return result != -1L
    }

    fun readAllStudents(): Cursor {
        val db = this.readableDatabase
        return db.rawQuery("SELECT * FROM $TABLE_NAME", null)
    }

    fun updateStudent(rollNumber: String, name: String, marks: Int): Boolean {
        val db = this.writableDatabase
        val contentValues = ContentValues()
        contentValues.put(COLUMN_NAME, name)
        contentValues.put(COLUMN_MARKS, marks)
        val result = db.update(TABLE_NAME, contentValues, "$COLUMN_ROLL_NUMBER = ?", arrayOf(rollNumber))
        return result != -1
    }

    fun deleteStudent(rollNumber: String): Boolean {
        val db = this.writableDatabase
        val result = db.delete(TABLE_NAME, "$COLUMN_ROLL_NUMBER = ?", arrayOf(rollNumber))
        return result != -1
    }
}

在主要活动中

这样做

package com.example.androidstudio
import DatabaseHelper
import android.content.Context
import android.database.Cursor
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    fun showAlert(context: Context, title: String, message: String) {
        val builder = AlertDialog.Builder(context)
        builder.setTitle(title)
        builder.setMessage(message)

        builder.setPositiveButton("OK") { dialog, _ ->
            dialog.dismiss()
        }
        val dialog = builder.create()
        dialog.show()
    }
    private lateinit var databaseHelper: DatabaseHelper

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

        databaseHelper = DatabaseHelper(this)

        val rollNumberEditText = findViewById<EditText>(R.id.rollNumberEditText)
        val nameEditText = findViewById<EditText>(R.id.nameEditText)
        val marksEditText = findViewById<EditText>(R.id.marksEditText)
        val addButton = findViewById<Button>(R.id.addButton)
        val displayButton = findViewById<Button>(R.id.displayButton)
        val updatestudent = findViewById<Button>(R.id.updatestudent)
        val deletestudent = findViewById<Button>(R.id.deletestudent)
        updatestudent.setOnClickListener {
            val rollNumber = rollNumberEditText.text.toString()
            val name = nameEditText.text.toString()
            val marks = marksEditText.text.toString()

            if (rollNumber.isNotEmpty() && name.isNotEmpty() && marks.isNotEmpty()) {
                if (databaseHelper.updateStudent(rollNumber, name, marks.toInt())) {
                    Toast.makeText(this, "Updated Student Successfully", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Failed to update student", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
            }

        }

        deletestudent.setOnClickListener {
            val rollNumber = rollNumberEditText.text.toString()

            if (rollNumber.isNotEmpty()) {
                if (databaseHelper.deleteStudent(rollNumber)) {
                    Toast.makeText(this, "Deleted Student Successfully", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Failed to delete student", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "Please fill in roll number field", Toast.LENGTH_SHORT).show()
            }
        }
        addButton.setOnClickListener {
            val rollNumber = rollNumberEditText.text.toString()
            val name = nameEditText.text.toString()
            val marks = marksEditText.text.toString()

            if (rollNumber.isNotEmpty() && name.isNotEmpty() && marks.isNotEmpty()) {
                if (databaseHelper.addStudent(rollNumber, name, marks.toInt())) {
                    Toast.makeText(this, "Student added successfully", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this, "Failed to add student", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_SHORT).show()
            }
        }

        displayButton.setOnClickListener {
            val cursor: Cursor = databaseHelper.readAllStudents()
            if (cursor.count == 0) {
                Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val displayString = StringBuilder()
            while (cursor.moveToNext()) {
                val rollNumber = cursor.getString(0)
                val name = cursor.getString(1)
                val marks = cursor.getInt(2)
                displayString.append("Roll Number: $rollNumber, Name: $name, Marks: $marks\n")
            }
            showAlert(this,"Selected Items", displayString.toString())
        }
    }

    override fun onDestroy() {
        databaseHelper.close()
        super.onDestroy()
    }
}

查找特定输入

displayButton.setOnClickListener {
        val name2 = nameEditText.text.toString()
           val cursor2: Cursor = databaseHelper.findtotstudents(name2)
            if (cursor2.count == 0) {
                Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val displayString2 = StringBuilder()
            while (cursor2.moveToNext()) {
                val count = cursor2.getString(0)
                displayString2.append("Count is $count")
            }
            showAlert(this,"Count Items", displayString2.toString())
        }
    }

FUNCTION IN databaseHelper is 

fun findtotstudents(name: String): Cursor {
        val db = this.readableDatabase
        return db.rawQuery("SELECT COUNT(roll_number) FROM $TABLE_NAME WHERE name= + \"$name\"", null)
    }

选择相似名称的卷数

MainActivity.kt 

displayButton.setOnClickListener {
 
val cursor2: Cursor = databaseHelper.checkeachcount()
            if (cursor2.count == 0) {
                Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val displayString2 = StringBuilder()
            while (cursor2.moveToNext()) {
                val count = cursor2.getString(1)
                val name = cursor2.getString(0)
                displayString2.append("Name : $name, Count: $count")
            }
            showAlert(this,"Name and Count", displayString2.toString())
        }

DatabaseHelper

    fun checkeachcount(): Cursor {
        val db = this.readableDatabase
        return db.rawQuery("SELECT name, COUNT(roll_number) FROM $TABLE_NAME GROUP BY name", null)
    }

选择分数最高的学生和分数最低的学生的姓名和分数

DatabaseHelper

    fun findmaxstudent(): Cursor {
        val db = this.readableDatabase
        return db.rawQuery("SELECT name, marks FROM $TABLE_NAME a WHERE a.marks = (SELECT MAX(MARKS) FROM $TABLE_NAME)",null)
    }

    fun findminstudent(): Cursor {
        val db = this.readableDatabase
        return db.rawQuery("SELECT name, marks FROM $TABLE_NAME a WHERE a.marks = (SELECT MIN(MARKS) FROM $TABLE_NAME)",null)
    }

MainActivity 

 displayButton.setOnClickListener {


            val cursor2: Cursor = databaseHelper.findmaxstudent()
            if (cursor2.count == 0) {
                Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val displayString2 = StringBuilder()
            while (cursor2.moveToNext()) {
                val maxmarks = cursor2.getString(1)
                val name = cursor2.getString(0)
                displayString2.append("Name : $name, Max Marks: $maxmarks\n")
            }
            val cursor: Cursor = databaseHelper.findminstudent()
            if (cursor.count == 0) {
                Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            while (cursor.moveToNext()) {
                val minmarks = cursor.getString(1)
                val name = cursor.getString(0)
                displayString2.append("Name : $name, Min Marks: $minmarks\n")
            }
            showAlert(this,"Name and Count", displayString2.toString())
        }

列表视图中的数据库显示

displayall.setOnClickListener {
            var arr = emptyArray<String>()
            val cursor: Cursor = databaseHelper.readAllStudents()
            if (cursor.count == 0) {
                Toast.makeText(this, "No students to display", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            while (cursor.moveToNext()) {
                val rollNumber = cursor.getString(0)
                val name = cursor.getString(1)
                val marks = cursor.getInt(2)
                arr+= rollNumber + "  "+name+"  "+marks
            }
            var adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,arr)
            ls.adapter = adapter

        }

将数据库添加到 Spinner

var spinner = findViewById<Spinner>(R.id.spinner)
        var arr = emptyArray<String>()
        val cursor: Cursor = databaseHelper.getcountries()
        if (cursor.count == 0) {
            Toast.makeText(this, "Nothing to display", Toast.LENGTH_SHORT).show()
        }
        while (cursor.moveToNext()) {
            val countrytemp = cursor.getString(0)
            arr+= countrytemp
        }
        var adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,arr)
        spinner.adapter = adapter
        var selectedItem = ""
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                selectedItem = parent?.getItemAtPosition(position).toString()
                Toast.makeText(this@SecondActivity, selectedItem, Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }
        }

检查此链接以获取其他视图 - Kotlin 代码报告“无法使用提供的参数调用以下函数”

© www.soinside.com 2019 - 2024. All rights reserved.