Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在适配器-android中观察livedata时出现问题_Android_Kotlin_Android Recyclerview_Adapter - Fatal编程技术网

在适配器-android中观察livedata时出现问题

在适配器-android中观察livedata时出现问题,android,kotlin,android-recyclerview,adapter,Android,Kotlin,Android Recyclerview,Adapter,我会给你一些我的应用程序的提示,也许对我的问题有帮助 我有一个改造过的Api,我会得到这些数据。然后将所有数据插入roomdatabase 在带有recyclerview的主屏幕中,我显示所有这些产品(数据) 在每个产品附近,我都有一个按钮,用于将产品发送到购物车片段。还有一个值(textview)用于保存每个按钮,以显示有多少项目转到购物车片段 我使用upsert(事务)插入或更新产品到购物车片段 然后,使用obvserver livedata显示发送到购物车的产品的金额值 首先,我需要一种方

我会给你一些我的应用程序的提示,也许对我的问题有帮助

我有一个改造过的Api,我会得到这些数据。然后将所有数据插入roomdatabase

在带有recyclerview的主屏幕中,我显示所有这些产品(数据)

在每个产品附近,我都有一个按钮,用于将产品发送到购物车片段。还有一个值(textview)用于保存每个按钮,以显示有多少项目转到购物车片段

我使用upsert(事务)插入或更新产品到购物车片段

然后,使用obvserver livedata显示发送到购物车的产品的金额值

首先,我需要一种方法来实现主屏幕中的观察实时数据,而不是适配器/以及我的upsert查询是否正确?有时,当点击产品按钮时,其他产品的价值会发生变化

这是我的密码:

道:

//这是用于Maintable的
@查询(“从主菜单中选择*)
fun getalldata():LiveData
//推车台
@查询(“从购物车中选择*)
趣味getAllFromCart():LiveData
@查询(“从购物车中选择*,其中id=:int”)
趣味GetAllFromCart(int:int):LiveData
@插入(onConflict=OnConflictStrategy.IGNORE)
趣味插画(型号:CartTable):长
@查询(“更新购物车设置金额=金额+1,其中id=:int”)
趣味updateCart(int:int)
@交易
fun upsert(型号:CartTable){
val id=insertToCart(型号)
如果(id==-1L){
模特,身份证?,让我看看{
updateCart(it)
}
主适配器:


class RecyclerAdapterMain(


    private val product: List<Roomtable>,
    val context: Context,
    private val viewlifecyclerOwner: LifecycleOwner

) :

    RecyclerView.Adapter<RecyclerAdapterMain.ViewHolder>() {


    val viewModel: ViewModelRoom by lazy {

        ViewModelProvider.AndroidViewModelFactory(Application()).create(ViewModelRoom::class.java)

    }


    inner class ViewHolder(itemview: View) :
        RecyclerView.ViewHolder(itemview) {


        val title: TextView = itemview.product_txt

        val price: TextView = itemview.price_product

        val imageproduct: ImageView = itemview.product_image

        val btn_add_product: Button = itemview.btn_add_product

        var amount_value: TextView = itemview.amount_value
    


    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {


        val layoutview =
            LayoutInflater.from(parent.context).inflate(R.layout.product_items, parent, false)
        return ViewHolder(layoutview)

    }

    override fun getItemCount(): Int = product.size


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {


        var products = product[position]

        holder.title.text = products.title
        holder.price.text = products.price
        Picasso.get().load(products.image).into(holder.imageproduct)



        holder.btn_add_product.setOnClickListener {

            products.amount++

            viewModel.upsert(
                CartTable(
                    holder.adapterPosition,
                    products.title,
                    products.price,
                    products.image,
                    products.amount
                )
            )


            viewModel.GetallFromCart(holder.adapterPosition).observe(viewlifecyclerOwner, Observer {

                if (it != null) {

                    for (item in it) {

                        holder.amount_value.text = item.amount.toString()

                    }

                }

            })

        }

分类回收器daptermain(
私人val产品:列表,
val context:context,
private val ViewLifecycleOwner:LifecycleOwner
) :
RecyclerView.Adapter(){
val viewModel:lazy的ViewModelRoom{
ViewModelProvider.AndroidViewModelFactory(应用程序()).create(ViewModelRoom::class.java)
}
内部类ViewHolder(itemview:View):
RecyclerView.ViewHolder(itemview){
val标题:TextView=itemview.product_txt
val价格:TextView=itemview.price\u产品
val imageproduct:ImageView=itemview.product\u图像
val btn_add_product:Button=itemview.btn_add_product
var amount\u value:TextView=itemview.amount\u value
}
override onCreateViewHolder(父级:ViewGroup,viewType:Int):ViewHolder{
val布局视图=
LayoutFlater.from(parent.context)。充气(R.layout.product\u项,parent,false)
返回视图保持架(布局视图)
}
重写getItemCount():Int=product.size
覆盖BindViewHolder(holder:ViewHolder,位置:Int){
var产品=产品[职位]
holder.title.text=产品.title
holder.price.text=产品.price
Picasso.get().load(products.image).into(holder.imageproduct)
holder.btn\u add\u product.setOnClickListener{
产品数量++
viewModel.upsert(
手推车(
支架。适配器位置,
产品名称,
产品、价格、,
产品,形象,,
产品数量
)
)
viewModel.GetallFromCart(支架.适配器位置)。观察(viewlifecyclerOwner,Observer{
如果(it!=null){
对于(其中的项目){
holder.amount\u value.text=item.amount.toString()
}
}
})
}
主要活动:


class HomeActivity : AppCompatActivity(){


    val viewModel: ViewModelRoom by lazy {

        ViewModelProvider(this).get(ViewModelRoom::class.java)


    }



    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.home_activity)


        loadProduct()


    @RequiresApi(Build.VERSION_CODES.M)
    private fun loadProduct() {

        swipeRefreshMain.isRefreshing = true

        if (hasNetworkAvilable(applicationContext)) {

            viewModel.setup()
            viewModel.products.observe(this, Observer {

                loadrecycler(it)

            })

        } else {

            Toast.makeText(
                applicationContext,
                "برای بروز رسانی محصولات اینترنت خود را روشن کنید",
                Toast.LENGTH_LONG
            ).show()
            viewModel.getalldata().observe(this, Observer {

                if (!it.isNullOrEmpty()) {

                    loadrecycler(it)


                } else {


                    val builder = AlertDialog.Builder(this)
                        .setView(R.layout.customalertdialog)
                        .setPositiveButton("Ok", null)
                        .create()
                        .show()

                    val constraint = Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build()
                    val workmanager: WorkManager = WorkManager.getInstance(this)
                    val workRequest = OneTimeWorkRequest.Builder(UploadWorkerClass::class.java)
                        .setConstraints(constraint)
                        .build()
                    workmanager.enqueue(workRequest)


                }

            })


        }
    }

    fun loadrecycler(product: List<Roomtable>) {


        val swipeRefreshLayout: SwipeRefreshLayout = findViewById(R.id.swipeRefreshMain)
        val recycler: RecyclerView = findViewById(R.id.recycler_main)

        recycler.apply {


            layoutManager = GridLayoutManager(this@HomeActivity, 2)

            adapter = RecyclerAdapterMain(
                product, this@HomeActivity, this@HomeActivity )


            Handler(Looper.getMainLooper()).postDelayed({

                swipeRefreshLayout.isRefreshing = false

            }, randomInRange(1, 3) * 1000.toLong())

        }
    }

}



    

















类HomeActivity:AppCompatActivity(){
val viewModel:lazy的ViewModelRoom{
ViewModelProvider(this.get)(ViewModelRoom::class.java)
}
@RequiresApi(Build.VERSION\u CODES.M)
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.home_活动)
loadProduct()
@RequiresApi(Build.VERSION\u CODES.M)
私人娱乐产品(){
swipeRefreshMain.isRefreshing=true
if(具有网络可访问性(applicationContext)){
viewModel.setup()
viewModel.products.observe(此,观察者{
装载机回收器(it)
})
}否则{
Toast.makeText(
应用上下文,
"برای بروز رسانی محصولات اینترنت خود را روشن کنید",
吐司,长度
).show()
viewModel.getalldata().observe(这个,观察者{
如果(!it.isNullOrEmpty()){
装载机回收器(it)
}否则{
val builder=AlertDialog.builder(此)
.setView(R.layout.customalertdialog)
.setPositiveButton(“确定”,空)
.create()
.show()
val constraint=Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workmanager:workmanager=workmanager.getInstance(此)
val workRequest=OneTimeWorkRequest.Builder(UploadWorkerClass::class.java)
.setConstraints(约束)
.build()
workmanager.enqueue(工作请求)
}
})
}
}
趣味装载回收器(产品:列表){
val swipeRefreshLayout:swipeRefreshLayout=findViewById(R.id.swipeRefreshMain)
val recycler:RecyclerView=findViewById(R.id.recycler\u main)
回收商。申请{
layoutManager=GridLayoutManager(this@HomeActivity, 2)
适配器=RecyclerAdapterMain(
产品,,this@HomeActivity, this@HomeActivity )
处理程序(Looper.getMainLooper()).postDelayed({
swipeRefreshLayout.isRefreshing=false
},Randominrong

class HomeActivity : AppCompatActivity(){


    val viewModel: ViewModelRoom by lazy {

        ViewModelProvider(this).get(ViewModelRoom::class.java)


    }



    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.home_activity)


        loadProduct()


    @RequiresApi(Build.VERSION_CODES.M)
    private fun loadProduct() {

        swipeRefreshMain.isRefreshing = true

        if (hasNetworkAvilable(applicationContext)) {

            viewModel.setup()
            viewModel.products.observe(this, Observer {

                loadrecycler(it)

            })

        } else {

            Toast.makeText(
                applicationContext,
                "برای بروز رسانی محصولات اینترنت خود را روشن کنید",
                Toast.LENGTH_LONG
            ).show()
            viewModel.getalldata().observe(this, Observer {

                if (!it.isNullOrEmpty()) {

                    loadrecycler(it)


                } else {


                    val builder = AlertDialog.Builder(this)
                        .setView(R.layout.customalertdialog)
                        .setPositiveButton("Ok", null)
                        .create()
                        .show()

                    val constraint = Constraints.Builder()
                        .setRequiredNetworkType(NetworkType.CONNECTED)
                        .build()
                    val workmanager: WorkManager = WorkManager.getInstance(this)
                    val workRequest = OneTimeWorkRequest.Builder(UploadWorkerClass::class.java)
                        .setConstraints(constraint)
                        .build()
                    workmanager.enqueue(workRequest)


                }

            })


        }
    }

    fun loadrecycler(product: List<Roomtable>) {


        val swipeRefreshLayout: SwipeRefreshLayout = findViewById(R.id.swipeRefreshMain)
        val recycler: RecyclerView = findViewById(R.id.recycler_main)

        recycler.apply {


            layoutManager = GridLayoutManager(this@HomeActivity, 2)

            adapter = RecyclerAdapterMain(
                product, this@HomeActivity, this@HomeActivity )


            Handler(Looper.getMainLooper()).postDelayed({

                swipeRefreshLayout.isRefreshing = false

            }, randomInRange(1, 3) * 1000.toLong())

        }
    }

}