本文介绍了如何从一个活动中获取edittext值到下一个活动的recyclerview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to fetch edittext value from one activity and displaying that text in recycleview and storing using room DB....

基本上,该想法是在单击时将地址添加到活动地址中,然后它将重定向到下一页,用户在提交该地址时将获得地址表格,它将获取地址并添加到先前的活动recycleview中.

Basically the idea is adding the address in activity address when clicks on plus it will redirect to next page where the user gets the address form onsubmit it will fetch address and add to previous activity 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
}

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活动:

AddAddressActivity activity:

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

AddressActivity:-

AddressActivity:-

     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活动:-

AddressAdapter activity:-

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
}

}

CustomApplication:

CustomApplication:

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

}

}

请帮助..我是Kotlin和Room db的新手.

please help ..I'm new to kotlin and room db..

推荐答案

abstract fun AddressDao(): AddressDao?

为什么这个可以为空?

val favoriteData: List<Table>?

为什么这个可以为空?

fun addData(favoriteList: Table?)

为什么这个可以为空?

fun delete(favoriteList: Table?)

为什么这个可以为空?

有类型的可空性使您能够表示给定值 可以 在何处为空,在某种意义上说不存在该值 strong>.

Typed nullability is to enable you to represent where a given value can be null, in the sense that it makes sense for it to be absent.

以上两种情况均不代表这种情况.房间永远不会让您返回null,而不是实际的dao.

Neither of the above cases represent such a scenario. Room will never return you null instead of an actual dao.

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

Kotlin's null safety is to allow you to eliminate potential error cases by making it part of the type system, it shouldn't be used to create "false" error cases such as these. If you're trying to add null to a database instead of a real object, you've probably got a bug in your code, and Kotlin should be able to help you eliminate that possibility.

关于您的实际问题,您在滥用会议室.

As for your actual question, you're misusing Room.

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

.allowMainThreadQueries() is a way to disable an error check, but that error is there for a reason. You're not supposed to be reading the data on the UI thread, because with enough data, your app will freeze (ANR).

代码应该看起来像这样:

The code is supposed to look something like this:

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

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

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

AddressAdapter:

AddressAdapter:

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活动:-

AddAddress activity:-

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

这篇关于如何从一个活动中获取edittext值到下一个活动的recyclerview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:07
查看更多