如何从一个活动中获取edittext值到下一个活动的recyclerview?

Posted

技术标签:

【中文标题】如何从一个活动中获取edittext值到下一个活动的recyclerview?【英文标题】:How to fetch edittext value from one activity to recyclerview of next activity? 【发布时间】:2020-11-24 08:24:43 【问题描述】:

我正在尝试从一项活动中获取 edittext 值,并在 recycleview 中显示该文本并使用房间数据库进行存储....

基本上,这个想法是在点击时在活动地址中添加地址,它会重定向到用户在提交时获取地址表单的下一页,它将获取地址并添加到以前的活动recycleview。

这是我的房间代码:

表格:---

@Entity(tableName = "address")
class Address 
@PrimaryKey
var id = 0

@ColumnInfo(name = "address")
var address: String? = null

数据库:-

@Database(entities = [Address::class], version = 1)
 abstract class Database : RoomDatabase() 
abstract fun AddressDao(): AddressDao

地址道:

@Dao
interface AddressDao 
@Insert
suspend fun addData(address: Address)



@Query("select * from address")
fun getAddressesWithChanges() :LiveData<List<Address>>

@Query("SELECT EXISTS (SELECT 1 FROM address WHERE id=:id)")
suspend fun isAddressAdded(id: Int): Int

@Delete
suspend fun delete(address: Address)

AddAddressActivity 活动:

   class AddAddressActivity : AppCompatActivity() 
    override fun onCreate(savedInstanceState: Bundle?) 
    super.onCreate(savedInstanceState)
    setContentView(R.layout.addaddress)

    val editText: EditText = findViewById(R.id.longaddress)

    val application = application as CustomApplication

    saveaddress.setOnClickListener 
        val address = Address()
        address.address = editText.getText().toString()

        lifecycleScope.launch 
            application.addressDao.addData(address)
            finish()
           
         
       
      

地址活动:-

     class AddressActivity : AppCompatActivity() 
      private val adapter = AddressAdapter()

     private lateinit var data: LiveData<List<Address>>

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

    addbutton.findViewById<View>(R.id.addbutton).setOnClickListener 
        val intent = Intent(this, AddAddressActivity::class.java)
        startActivity(intent)
    

    val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
    recyclerView.setHasFixedSize(true)
    recyclerView.layoutManager = LinearLayoutManager(this, 
    LinearLayoutManager.VERTICAL, false)
    recyclerView.adapter = adapter

    val application = application as CustomApplication
    data = application.database.AddressDao().getAddressesWithChanges()
    data.observe(this, Observer  words1 ->
        // Update the cached copy of the words in the adapter.
        words1?.let  adapter.updateData(it) )



  

AddressAdapter 活动:-

class AddressAdapter: RecyclerView.Adapter<AddressAdapter.ViewHolder>() 
private var addresses: List<Address> = Collections.emptyList()

override fun onCreateViewHolder(viewGroup: ViewGroup, itemViewType: Int): 
   ViewHolder =
  ViewHolder(LayoutInflater.from(viewGroup.context)
  .inflate(R.layout.address_item, viewGroup, false) )

override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) 
    val fl: Address = addresses[position]
    viewHolder.tv.setText(fl.address)


override fun getItemCount(): Int = addresses.size

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) 
    var tv: TextView

    init 
        tv = itemView.findViewById(R.id.ftv_name)
        

fun updateData(addresses:
               List<Address>) 
    this.addresses = addresses
    notifyDataSetChanged() // TODO: use ListAdapter if animations are needed

自定义应用程序:

class CustomApplication: Application() 
lateinit var database: Database
    private set
lateinit var addressDao: AddressDao
    private set

override fun onCreate() 
    super.onCreate()

    this.database = Room.databaseBuilder<Database>(
        applicationContext,
        Database::class.java, "database"
    ).build()


返回地址活动时列表不显示recycleview为空

请帮助..我是 kotlin 和房间数据库的新手..

【问题讨论】:

【参考方案1】:
abstract fun AddressDao(): AddressDao?

为什么这个可以为空?

val favoriteData: List<Table>?

为什么这个可以为空?

fun addData(favoriteList: Table?)

为什么这个可以为空?

fun delete(favoriteList: Table?)

为什么这个可以为空?


类型化的可空性是为了让您能够表示给定值可以为空的位置,因为它不存在是有意义的强>。

以上两种情况都不代表这种情况。 Room 将永远不会返回您 null 而不是实际的 dao

Kotlin 的 null 安全性允许您通过使其成为类型系统的一部分来消除潜在的错误情况,它不应该用于创建诸如此类的“错误”错误情况。如果您尝试将 null 添加到数据库而不是真实对象,那么您的代码中可能存在错误,Kotlin 应该能够帮助您消除这种可能性。



至于您的实际问题,您误用了 Room。

.allowMainThreadQueries() 是一种禁用错误检查的方法,但该错误的存在是有原因的。您不应该在 UI 线程上读取数据,因为有足够的数据,您的应用将冻结 (ANR)。

代码应该是这样的:

@Entity(tableName = "address")
class Address 
    @PrimaryKey
    var id = 0

    @ColumnInfo(name = "address")
    var address: String? = null

数据库:-

@Database(entities = [Address::class], version = 1)
abstract class Database : RoomDatabase() 
    abstract fun addressDao(): AddressDao

地址道:

@Dao
interface AddressDao 
    @Insert
    suspend fun addData(address: Address)

    @Query("select * from address")
    fun getAddressesWithChanges(): LiveData<List<Address>>

    @Query("SELECT EXISTS (SELECT 1 FROM address WHERE id=:id)")
    suspend fun isAddressAdded(id: Int): Int

    @Delete
    suspend fun delete(address: Address)



class CustomApplication: Application() 
    lateinit var database: Database
        private set
    lateinit var addressDao: AddressDao
        private set
    
    override fun onCreate() 
        super.onCreate()

        this.database = Room.databaseBuilder<Database>(
            applicationContext,
            Database::class.java, "database"
        ).build()

        addressDao = database.addressDao()
    

androidManifest.xml

<application android:name=".CustomApplication"
    ...

地址活动:

import androidx.lifecycle.observe

class AddressActivity : AppCompatActivity() 
    private val adapter = AddressAdapter()

    private lateinit var data: LiveData<List<Address>>

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.address_activity)
 
        findViewById<View>(R.id.addButton).setOnClickListener 
            val intent = Intent(this, AddAddressActivity::class.java)
            startActivity(intent)
        

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        recyclerView.adapter = adapter

        val application = application as CustomApplication
        val addressDao = application.addressDao 

        data = addressDao.getAddressesWithChanges()
        data.observe(this) 
            adapter.updateData(it)
        
    

地址适配器:

class AddressAdapter: RecyclerView.Adapter<AddressAdapter.ViewHolder>() 
    private var addresses: List<Table> = Collections.emptyList()

    override fun onCreateViewHolder(viewGroup: ViewGroup, itemViewType: Int): ViewHolder =
        ViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.address_item, viewGroup, false))

    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) 
        val address = addresses[position]
        viewHolder.tv.setText(address.address)
    

    override fun getItemCount(): Int = addresses.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) 
        val tv = itemView.findViewById(R.id.ftv_name)
    

    fun updateData(addresses: List<Address>) 
        this.addresses = addresses
        notifyDataSetChanged() // TODO: use ListAdapter if animations are needed
    

AddAddress 活动:-

class AddAddressActivity : AppCompatActivity() 
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.addaddress)

        val editText: EditText = findViewById(R.id.longaddress)

        val application = application as CustomApplication
        val addressDao = application.addressDao
        
        saveaddress.setOnClickListener 
            val address = Address()
            address.address = editText.getText().toString()

            lifecycleScope.launch 
                addressDao.addData(address)
                finish()
            
        
    

您也可以参考https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#6

【讨论】:

有了最新的 Jetpack 东西和在该块顶部的导入,这两个应该都能正常工作。 我不明白...我只使用最新的 解决了一个错误...上面的错误仍然存​​在...帮助@EpicPandaForce IDE 告诉你错误,我不知道它来自这里。如果您指定 IDE 在您将鼠标悬停在它上面时告诉您的内容,那么我可能会提供帮助。 是的,这样做@PrimaryKey(autoGenerate = true) 然后卸载应用程序后它工作了..非常感谢【参考方案2】:

请将您的行替换为

  val  rv=findViewById<RecyclerView>(R.id.recyclerview)

你传递了错误的 id addres-s-recyclerview 这就是它分配 null 的原因

【讨论】:

请接受这个答案并请发布一个新问题,因为原来的异常现在已经解决了。 没有问题 -->how-to-fetch-edittext-value-from-one-activity-to-recyclerview-of-next-activity...帮帮我 我的应用程序没有崩溃......但是recycleview是空的......请帮助,..我是roomdb的新手

以上是关于如何从一个活动中获取edittext值到下一个活动的recyclerview?的主要内容,如果未能解决你的问题,请参考以下文章

如何从存储在数据库中的 Listview 获取值到另一个活动?使用 Android 和 Mysql

从适配器类获取不同活动中的 EditText 值

如何使用 bundle 一次从多个活动中获取数据

无法从edittext获取值到字符串

我如何使用意图从列表视图转到下一个活动? [复制]

我如何将 otp 对象从服务器传递到下一个活动