我试图创建一个简单的应用程序,用户可以在其中输入文本到编辑文本字段.按下按钮后,输入内容就会保存到SQLite数据库中.

我遵循了以下链接中的指南(并try 适应我的应用程序):

https://www.geeksforgeeks.org/android-sqlite-database-in-kotlin/

然而,当在Android Studio中运行应用程序时,我得到错误:

Type mismatch: inferred type is AddRecipeFragment but Context was expected

我的AddRecipeFragment.kt写道:

package com.example.recipy

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.recipy.databinding.FragmentAddRecipeBinding


class AddRecipeFragment : Fragment() {

    private var _binding: FragmentAddRecipeBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        _binding = FragmentAddRecipeBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

//        val saveRecipeButton = findViewById(R.id.save_recipe_button) as Button
        binding.saveRecipeButton.setOnClickListener{

            val db = DBHelper(this, null)
            val name = binding.recipeNameTextInput.text.toString()

            db.addRecipe(name)

            Toast.makeText(this, name + " added to database", Toast.LENGTH_LONG).show()

            binding.recipeNameTextInput.text.clear()
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

我的fragment_add_recipe.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddRecipeFragment">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <EditText
        android:id="@+id/recipe_name_text_input"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:inputType="text"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/save_recipe_button"
        android:layout_width="150sp"
        android:layout_gravity="center"
        android:text="Save"
        android:textColor="#ffffff"
        android:textSize="20sp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        app:layout_constraintTop_toBottomOf="@id/Name"/>

    <TextView
        android:id="@+id/Name"
        android:textAlignment="center"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20sp"
        android:text="Name\n\n"
        android:textSize="22sp"
        android:padding="10sp"
        android:textColor="#000000"
        app:layout_constraintTop_toBottomOf="@id/recipe_name_text_input"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

和DBHelper.kt:

package com.example.recipy

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

public class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) :
    SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) {

    // below is the method for creating a database by a sqlite query
    override fun onCreate(db: SQLiteDatabase) {

        val query = ("CREATE TABLE " + TABLE_NAME + " ("
                + ID_COL + " INTEGER PRIMARY KEY, " +
                NAME_COl + " TEXT," + ")")
        
        db.execSQL(query)
    }

    override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) {
        // this method is to check if table already exists
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
        onCreate(db)
    }

    // This method is for adding data in our database
    fun addRecipe(name : String){
        
        val values = ContentValues()
        
        values.put(NAME_COl, name)
        
        val db = this.writableDatabase
        
        db.insert(TABLE_NAME, null, values)

        db.close()
    }


    companion object{
        // here we have defined variables for our database

        // below is variable for database name
        private val DATABASE_NAME = "RECIPY_DB"

        // below is the variable for database version
        private val DATABASE_VERSION = 1

        // below is the variable for table name
        val TABLE_NAME = "recipes_table"

        // below is the variable for id column
        val ID_COL = "id"

        // below is the variable for name column
        val NAME_COl = "name"
    }
}

推荐答案

我遵循了以下链接中的指南(并try 适应我的应用程序)

该指南不使用碎片.它从Activity实例化DBHelper.ActivityContext的子类.

然而,当在Android Studio中运行该应用程序时,我收到错误:Type mismatch: inferred type is AddRecipeFragment but Context was expected

您复制并粘贴该行以实例化DBHelper,但将其粘贴到Fragment中.Fragment不是从Context延伸出来的,所以this不是Context,正如DBHelper所期望的那样.

您可以使用requireContext()代替this:

val db = DBHelper(requireContext(), null)

话虽如此,我真的建议你使用更完整的资源来学习Android,比如书籍和课程.该指南关注的是Android应用程序开发的一个小方面,它提出的建议相当糟糕.无论你try my free books还是别的什么,都可以找到一些资源来教你现代Android应用程序开发,包括线程(例如Kotlin协程)、react 式API(例如Kotlin Flow)、生命周期管理(例如ViewModel)以及类似的主题.

Android相关问答推荐

如何在Android Emulator上从物理设备接收TCP消息

如何在"不同活动"中添加不同按钮?

在Jetpack Compose中,material 3 Textfield上的底部边框 colored颜色 是如何更改的?

如何使可拖动内容停留在可组合框的边界内

默认调度程序是否在协程中使用共享线程池?

在Jetpack Compose中从LazyColumn中删除项目时发生IndexOutOf边界异常

如何从URI中获取图像大小

在柯特林连续测量网速

找不到com.android.tools.build:gradle:8.0

Android v31 及更低版本中 ImageView 中的圆角

使用不同的gradle文件导入外部库

Jetpack Compose:在屏幕外制作长水平图像的动画

Compose 状态不是 recomposing

如何在 Jetpack Compose 中创建无限pager

从活动共享视图模型以使用 hilt 组合函数

从 Firebase 云存储中获取照片会导致 Android Jetpack Compose 闪烁

没有互联网连接时,Firebase Storage putFile() 永远不会完成

在 Room 中创建一对多关系时,@Relation 类是什么意思?

可扩展性 Qt 5.15 Android

如何获取 Material Design 3 的底部导航栏高度?