Android Studio中的Recycler View没有显示任何内容。

huangapple go评论72阅读模式
英文:

Android Studio Recycler View doesn't show anything

问题

I tried creating a simple room database in kotlin. The code seems to work just fine but i can't manage to show the list of the items i added in the recycler view.

Here is my main fragment:

package com.ebookfrenzy.roomdemo.ui.main

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import com.ebookfrenzy.roomdemo.ProductRepository
import com.ebookfrenzy.roomdemo.MainActivity
import com.ebookfrenzy.roomdemo.ProductDao
import com.ebookfrenzy.roomdemo.ui.main.ProductListAdapter
import android.view.ViewGroup
import com.ebookfrenzy.roomdemo.R
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.ebookfrenzy.roomdemo.Product
import androidx.fragment.app.viewModels
import java.util.*
import com.ebookfrenzy.roomdemo.databinding.FragmentMainBinding

//preparation du main fragment
class MainFragment : Fragment() {

    private var adapter: ProductListAdapter? = null

    companion object {
        fun newInstance() = MainFragment()
    }

    val viewModel: MainViewModel by viewModels()
    private var _binding: FragmentMainBinding? = null
    private val binding get() = _binding!!

    // si ya une erreur c'est ici
    private fun recyclerSetup(){
        adapter = ProductListAdapter(R.layout.product_list_item)
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.recyclerView.adapter = adapter

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentMainBinding.inflate(inflater, container, false)
        return binding.root
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        listenerSetup()
        observerSetup()
        recyclerSetup()
    }

    private fun clearFields() {
        binding.productID.text = ""
        binding.productName.setText("")
        binding.productQuantity.setText("")
    }

    //ajout de bouton listeners
    private fun listenerSetup() {
        binding.addButton.setOnClickListener {
            val name = binding.productName.text.toString()
            val quantity = binding.productQuantity.text.toString()

            if (name != "" && quantity != "") {
                val product = Product(name, Integer.parseInt(quantity))
                viewModel.insertProduct(product)
                clearFields()
            } else {
                binding.productID.text = " Infos Incompletes "
            }
        }
        binding.findButton.setOnClickListener {
            viewModel.findProduct(binding.productName.text.toString())
        }

        binding.deleteButton.setOnClickListener {
            viewModel.deleteProduct(
                binding.productName.text.toString()
            )
            clearFields()
        }

    }

    private fun observerSetup() {
        viewModel.getAllProducts()
            ?.observe(viewLifecycleOwner, Observer { products -> products?.let { adapter?.setProductList(it) } })
        viewModel.getSearchResults().observe(viewLifecycleOwner, Observer { products ->
            products?.let {
                if(it.isNotEmpty()){
                    binding.productID.text = String .format(Locale.US, "%d", it[0].id)
                    binding.productName.setText(it[0].productName)
                    binding.productQuantity.setText(String.format(Locale.US,"%d",it[0].quantity))
                }
                else {
                    binding.productID.text = "No Match"
                }
            }
        })
    }
}

Here is my adapter:

package com.ebookfrenzy.roomdemo.ui.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewParent
import android.widget.TextView
import androidx.appcompat.view.menu.MenuView.ItemView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.ebookfrenzy.roomdemo.Product
import com.ebookfrenzy.roomdemo.R

class ProductListAdapter(private val productItemLayout: Int): RecyclerView.Adapter<ProductListAdapter.ViewHolder>() {

    private var productList : List<Product>? = null

    override fun onBindViewHolder(holder: ViewHolder, listPosition:Int){
        val item = holder.item
        productList?.let {
            item.text = it!![listPosition].productName
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType:Int):ViewHolder{
        val view = LayoutInflater.from(parent.context).inflate(productItemLayout, parent, false )
        return ViewHolder(view)
    }

    fun setProductList(products : List<Product>){
        productList = products
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return if (productList==null) 0 else productList!!.size
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        var item : TextView = itemView.findViewById(R.id.product_row)
    }
}

Here is the design of the main fragment XML:

Android Studio中的Recycler View没有显示任何内容。

vs what it shows in the emulator:

Android Studio中的Recycler View没有显示任何内容。

Finally, here is the logcat:

2023-02-06 13:33:13.886 5565-5565/? I/frenzy.roomdemo: Late-enabling -Xcheck:jni
2023-02-06 13:33:13.924 5565-5565/? W/frenzy.roomdemo: Unexpected CPU variant for x86: x86_64.
    Known variants: atom, sandybridge, silvermont, kabylake, default
...

All my code is in Kotlin, and I followed a tutorial from a book. Instead of viewLifecycleOwner in the observer function, the book replaces it with "this," but Android Studio reports it as an error and suggests replacing it with lifeCycleOwner.

英文:

I tried creating a simple room database in kotlin. The code seems to work just fine but i can't manage to show the list of the items i added in the recycler view.

Here is my main fragment :

package com.ebookfrenzy.roomdemo.ui.main
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import com.ebookfrenzy.roomdemo.ProductRepository
import com.ebookfrenzy.roomdemo.MainActivity
import com.ebookfrenzy.roomdemo.ProductDao
import com.ebookfrenzy.roomdemo.ui.main.ProductListAdapter
import android.view.ViewGroup
import com.ebookfrenzy.roomdemo.R
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.ebookfrenzy.roomdemo.Product
import androidx.fragment.app.viewModels
import java.util.*
import com.ebookfrenzy.roomdemo.databinding.FragmentMainBinding
//preparation du main fragment
class MainFragment : Fragment() {
private var adapter: ProductListAdapter? = null
companion object {
fun newInstance() = MainFragment()
}
val viewModel: MainViewModel by viewModels()
private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!
// si ya une erreur c&#39;est ici
private fun recyclerSetup(){
adapter = ProductListAdapter(R.layout.product_list_item)
binding.recyclerView.layoutManager = LinearLayoutManager(context)
binding.recyclerView.adapter = adapter
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
@Deprecated(&quot;Deprecated in Java&quot;)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
listenerSetup()
observerSetup()
recyclerSetup()
}
private fun clearFields() {
binding.productID.text = &quot;&quot;
binding.productName.setText(&quot;&quot;)
binding.productQuantity.setText(&quot;&quot;)
}
//ajout de bouton listeners
private fun listenerSetup() {
binding.addButton.setOnClickListener {
val name = binding.productName.text.toString()
val quantity = binding.productQuantity.text.toString()
if (name != &quot;&quot; &amp;&amp; quantity != &quot;&quot;) {
val product = Product(name, Integer.parseInt(quantity))
viewModel.insertProduct(product)
clearFields()
} else {
binding.productID.text = &quot; Infos Incompletes &quot;
}
}
binding.findButton.setOnClickListener {
viewModel.findProduct(binding.productName.text.toString())
}
binding.deleteButton.setOnClickListener {
viewModel.deleteProduct(
binding.productName.text.toString()
)
clearFields()
}
}
private fun observerSetup() {
viewModel.getAllProducts()
?.observe(viewLifecycleOwner, Observer { products -&gt; products?.let { adapter?.setProductList(it) } })
viewModel.getSearchResults().observe(viewLifecycleOwner, Observer { products -&gt;
products?.let {
if(it.isNotEmpty()){
binding.productID.text = String .format(Locale.US, &quot;%d&quot;, it[0].id)
binding.productName.setText(it[0].productName)
binding.productQuantity.setText(String.format(Locale.US,&quot;%d&quot;,it[0].quantity))
}
else {
binding.productID.text = &quot;No Match&quot;
}
}
})
}
}

Here is my adapter :

package com.ebookfrenzy.roomdemo.ui.main
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewParent
import android.widget.TextView
import androidx.appcompat.view.menu.MenuView.ItemView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.ebookfrenzy.roomdemo.Product
import com.ebookfrenzy.roomdemo.R
class ProductListAdapter(private val productItemLayout: Int): RecyclerView.Adapter&lt;ProductListAdapter.ViewHolder&gt;() {
private var productList : List&lt;Product&gt;? = null
override fun onBindViewHolder(holder: ViewHolder, listPosition:Int){
val item = holder.item
productList.let {
item.text = it!![listPosition].productName
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType:Int):ViewHolder{
val view = LayoutInflater.from(parent.context).inflate(productItemLayout, parent, false )
return ViewHolder(view)
}
fun setProductList(products : List&lt;Product&gt;){
productList = products
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return if (productList==null) 0 else productList!!.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var item : TextView = itemView.findViewById(R.id.product_row)
}
}

Here is the design of the main fragment xml :
Android Studio中的Recycler View没有显示任何内容。

vs what it shows in the emulator :
Android Studio中的Recycler View没有显示任何内容。

Finally, here is the logcat :

2023-02-06 13:33:13.886 5565-5565/? I/frenzy.roomdemo: Late-enabling -Xcheck:jni
2023-02-06 13:33:13.924 5565-5565/? W/frenzy.roomdemo: Unexpected CPU variant for x86: x86_64.
Known variants: atom, sandybridge, silvermont, kabylake, default
2023-02-06 13:33:14.005 5565-5565/? V/studio.deploy: Startup agent attached to VM
2023-02-06 13:33:13.992 5565-5565/? W/re-initialized&gt;: type=1400 audit(0.0:27): avc: granted { execute } for path=&quot;/data/data/com.ebookfrenzy.roomdemo/code_cache/startup_agents/69880af5-agent.so&quot; dev=&quot;dm-33&quot; ino=148166 scontext=u:r:untrusted_app:s0:c161,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c161,c256,c512,c768 tclass=file app=com.ebookfrenzy.roomdemo
2023-02-06 13:33:14.006 5565-5565/? V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-6b5afa68.jar
2023-02-06 13:33:14.014 5565-5565/? W/frenzy.roomdemo: DexFile /data/data/com.ebookfrenzy.roomdemo/code_cache/.studio/instruments-6b5afa68.jar is in boot class path but is not in a known location
2023-02-06 13:33:14.018 5565-5565/? V/studio.deploy: Applying transforms with cached classes
2023-02-06 13:33:14.040 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
2023-02-06 13:33:14.040 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
2023-02-06 13:33:14.045 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10161; state: ENABLED
2023-02-06 13:33:14.061 5565-5565/com.ebookfrenzy.roomdemo W/ziparchive: Unable to open &#39;/data/app/~~KuAqymfHPelK0HgMzmVTcw==/com.ebookfrenzy.roomdemo-Bh69_2PWAZtOQ6sAIZ3H0g==/base.dm&#39;: No such file or directory
2023-02-06 13:33:14.061 5565-5565/com.ebookfrenzy.roomdemo W/ziparchive: Unable to open &#39;/data/app/~~KuAqymfHPelK0HgMzmVTcw==/com.ebookfrenzy.roomdemo-Bh69_2PWAZtOQ6sAIZ3H0g==/base.dm&#39;: No such file or directory
2023-02-06 13:33:14.203 5565-5565/com.ebookfrenzy.roomdemo V/GraphicsEnvironment: ANGLE Developer option for &#39;com.ebookfrenzy.roomdemo&#39; set to: &#39;default&#39;
2023-02-06 13:33:14.204 5565-5565/com.ebookfrenzy.roomdemo V/GraphicsEnvironment: ANGLE GameManagerService for com.ebookfrenzy.roomdemo: false
2023-02-06 13:33:14.204 5565-5565/com.ebookfrenzy.roomdemo V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
2023-02-06 13:33:14.210 5565-5565/com.ebookfrenzy.roomdemo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2023-02-06 13:33:14.210 5565-5565/com.ebookfrenzy.roomdemo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2023-02-06 13:33:14.248 5565-5593/com.ebookfrenzy.roomdemo D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
2023-02-06 13:33:14.252 5565-5593/com.ebookfrenzy.roomdemo D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2023-02-06 13:33:14.258 5565-5593/com.ebookfrenzy.roomdemo D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
2023-02-06 13:33:14.444 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Accessing hidden method Landroid/view/View;-&gt;computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
2023-02-06 13:33:14.445 5565-5565/com.ebookfrenzy.roomdemo W/frenzy.roomdemo: Accessing hidden method Landroid/view/ViewGroup;-&gt;makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
2023-02-06 13:33:14.449 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 210923482; UID 10161; state: DISABLED
2023-02-06 13:33:14.449 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 37756858; UID 10161; state: ENABLED
2023-02-06 13:33:14.777 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: createUnique: call
2023-02-06 13:33:14.778 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: HostConnection::get() New Host Connection established 0x750c54ed0e10, tid 5591
2023-02-06 13:33:14.782 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma ANDROID_EMU_hwc_multi_configs GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
2023-02-06 13:33:14.786 5565-5591/com.ebookfrenzy.roomdemo W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2023-02-06 13:33:14.787 5565-5591/com.ebookfrenzy.roomdemo W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
2023-02-06 13:33:14.793 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: eglCreateContext: 0x750c54ed1f50: maj 2 min 0 rcv 2
2023-02-06 13:33:14.817 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: eglMakeCurrent: 0x750c54ed1f50: ver 2 0 (tinfo 0x750e7ba74080) (first time)
2023-02-06 13:33:14.827 5565-5591/com.ebookfrenzy.roomdemo I/Gralloc4: mapper 4.x is not supported
2023-02-06 13:33:14.827 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: createUnique: call
2023-02-06 13:33:14.828 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: HostConnection::get() New Host Connection established 0x750c54ed2b50, tid 5591
2023-02-06 13:33:14.828 5565-5591/com.ebookfrenzy.roomdemo D/goldfish-address-space: allocate: Ask for block of size 0x100
2023-02-06 13:33:14.828 5565-5591/com.ebookfrenzy.roomdemo D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f3ffe000 size 0x2000
2023-02-06 13:33:14.830 5565-5591/com.ebookfrenzy.roomdemo W/Gralloc4: allocator 4.x is not supported
2023-02-06 13:33:14.835 5565-5591/com.ebookfrenzy.roomdemo D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma ANDROID_EMU_hwc_multi_configs GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
2023-02-06 13:33:14.868 5565-5591/com.ebookfrenzy.roomdemo W/Parcel: Expecting binder but got null!
2023-02-06 13:33:24.302 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=1037.81ms min=1.98ms max=9269.97ms count=9
2023-02-06 13:33:24.456 5565-5565/com.ebookfrenzy.roomdemo D/CompatibilityChangeReporter: Compat change id reported: 163400105; UID 10161; state: ENABLED
2023-02-06 13:33:24.457 5565-5565/com.ebookfrenzy.roomdemo D/InputMethodManager: showSoftInput() view=androidx.appcompat.widget.AppCompatEditText{b0f2ed6 VFED..CL. .F.P..ID 373,0-953,124 #7f080153 app:id/productName aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
2023-02-06 13:33:24.472 5565-5565/com.ebookfrenzy.roomdemo I/AssistStructure: Flattened final assist data: 2804 bytes, containing 1 windows, 17 views
2023-02-06 13:33:24.505 5565-5565/com.ebookfrenzy.roomdemo W/OnBackInvokedCallback: OnBackInvokedCallback is not enabled for the application.
Set &#39;android:enableOnBackInvokedCallback=&quot;true&quot;&#39; in the application manifest.
2023-02-06 13:33:24.549 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:25.358 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=211.10ms min=20.19ms max=410.23ms count=5
2023-02-06 13:33:26.385 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=171.04ms min=19.31ms max=492.61ms count=6
2023-02-06 13:33:27.180 5565-5565/com.ebookfrenzy.roomdemo D/InputMethodManager: showSoftInput() view=androidx.appcompat.widget.AppCompatEditText{eaf0844 VFED..CL. .F.P..ID 373,0-953,124 #7f080154 app:id/productQuantity aid=1073741825} flags=0 reason=SHOW_SOFT_INPUT
2023-02-06 13:33:27.203 5565-5565/com.ebookfrenzy.roomdemo W/OnBackInvokedCallback: OnBackInvokedCallback is not enabled for the application.
Set &#39;android:enableOnBackInvokedCallback=&quot;true&quot;&#39; in the application manifest.
2023-02-06 13:33:27.207 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:27.207 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:27.687 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=216.73ms min=17.56ms max=500.45ms count=6
2023-02-06 13:33:28.701 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=506.88ms min=499.29ms max=514.47ms count=2
2023-02-06 13:33:29.486 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:29.706 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=43.48ms min=8.22ms max=500.77ms count=23
2023-02-06 13:33:30.970 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=38.23ms min=12.95ms max=500.55ms count=33
2023-02-06 13:33:32.321 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=450.48ms min=352.90ms max=500.27ms count=3
2023-02-06 13:33:32.347 5565-5565/com.ebookfrenzy.roomdemo W/OnBackInvokedCallback: OnBackInvokedCallback is not enabled for the application.
Set &#39;android:enableOnBackInvokedCallback=&quot;true&quot;&#39; in the application manifest.
2023-02-06 13:33:32.347 5565-5565/com.ebookfrenzy.roomdemo D/InsetsController: show(ime(), fromIme=true)
2023-02-06 13:33:35.122 5565-5591/com.ebookfrenzy.roomdemo D/EGL_emulation: app_time_stats: avg=1400.40ms min=34.21ms max=2766.59ms count=2

All my code is in kotlin, i saw that there was a topic of someone that had the same problem, but i couldn't manage to get it right.

EDIT : i followed a tutorial from a book, here is the part of the observerSetup() :

Android Studio中的Recycler View没有显示任何内容。

ps : instead of viewLifecycleOwner in the observer function, the book replaces it by "this" except that when i write "this", android studio reports it as an error and suggests to replace it by lifeCycleOwner

Thanks a lot for your time !

答案1

得分: 1

我认为你的问题是因为你在recyclerSetup()之前调用了observerSetup()recyclerSetup是你设置adapter的地方,对吧?但是在observerSetup中,你这样做:

viewModel.getAllProducts()
?.observe(viewLifecycleOwner, Observer { products ->
// 需要设置适配器!
products?.let { adapter?.setProductList(it) }
})

如果getAllProducts()返回的LiveData已经有值,那么它将立即调用adapter?.setProductList(it) - 因为你还没有分配adapter,所以什么都不会发生,因为它仍然是null。如果那个LiveData在你分配adapter之后不再更新,它就永远不会刷新显示。

没有看到你的其余代码,我不能确定,但我建议首先检查这个问题。最简单的方法是在recyclerSetup和你的观察者 lambda 中设置一些断点,或者只添加一些日志语句。然后你可以精确地看到哪个被调用,以及顺序是否会引起问题!

英文:

I think your issue is because you call observerSetup() before recyclerSetup(). recyclerSetup is where you set adapter, right? But in observerSetup you do this:

viewModel.getAllProducts()
?.observe(viewLifecycleOwner, Observer { products -&gt;
// requires adapter to be set!
products?.let { adapter?.setProductList(it) }
})

If the LiveData that getAllProducts() returns already has a value, then it will immediately call adapter?.setProductList(it) - and since you haven't assigned adapter yet, nothing will happen because it's still null. And if that LiveData doesn't update again after you assign adapter, it will never refresh the display.

Without seeing the rest of your code I can't say for sure, but I'd check that first. The easiest thing to do is debug the app and set some breakpoints in recyclerSetup and your observer lambda, or just add some logging statements. Then you can see exactly what gets called first and if the order will cause you problems!

答案2

得分: 0

需要将数据分配给适配器,因此在获取产品后添加以下代码:

adapter.setProductList(products)
  • 请将“products”替换为您的数组名称。
英文:

you need to assign your data to adapter so add

adapter.setProductList(products)

after getting your products

  • replace products with your array name

huangapple
  • 本文由 发表于 2023年2月6日 17:35:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定