Ashish Dawkhar
Ashish Dawkhar

Reputation: 151

How to show nested child data in recyclerview

I want to show the items node details in recyclerview, but i getting some error. I have tried many method, but i didn't get the uid of items in items node in databasereference. I am trying to get items uid in firebase database reference, but unable to do it.how to get items uid database reference object

mainactivity code


class MainActivity : AppCompatActivity() {

lateinit var recyclerView: RecyclerView

lateinit var layoutManager: RecyclerView.LayoutManager

lateinit var RecyclerAdapter: RecyclerAdapter
lateinit var databaseReference: DatabaseReference
var database: FirebaseDatabase? = null

lateinit var auth:FirebaseAuth

    var personlist = arrayListOf<Persons>()


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


    recyclerView = findViewById(R.id.recyclerpersonview)



    database = FirebaseDatabase.getInstance()
    auth = FirebaseAuth.getInstance()

     





 databaseReference=database?.reference!!.child("Users")
.child(auth.currentUser!!.uid).child("items")

                                                                             
    databaseReference.addValueEventListener(object 
:ValueEventListener{

        override fun onDataChange(snapshot: DataSnapshot) {
            try {

                for (items in snapshot.children) {
                    val item1 = items.getValue(Persons::class.java)
                    personlist.add(item1!!)
                }

            }catch (e:Exception){
                
    
  
 
 
    
Toast.makeText(this@MainActivity,e.message,Toast.LENGTH_SHORT).show()
            }

        }
        override fun onCancelled(error: DatabaseError) {
            Toast.makeText(this@MainActivity,"unable to load 
    data",Toast.LENGTH_SHORT).show()
        }


    })

    layoutManager = LinearLayoutManager(this)

    RecyclerAdapter = RecyclerAdapter(this, personlist)

    RecyclerAdapter.notifyDataSetChanged()

    recyclerView.adapter = RecyclerAdapter

    recyclerView.layoutManager = layoutManager

   }

  recycleradapter code


 class RecyclerAdapter(var context: MainActivity, var personlist: 
  ArrayList<Persons>) :
 RecyclerView.Adapter<RecyclerAdapter.Personviewholder>() {
 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): 
 Personviewholder {
    val view = 
 LayoutInflater.from(parent.context).inflate(R.layout.singlerow, 
parent, 
  false)

    return Personviewholder(view)
}

override fun getItemCount(): Int {
    return personlist.size
}

override fun onBindViewHolder(holder: Personviewholder, position: 
Int) {
    val view = personlist[position]
    holder.personname.text = view.personname
    holder.persondesc.text = view.persondesc
    
Picasso.with(context).load(view.personimage).into(holder.personimg)

    holder.layoutlist.setOnClickListener {
        val intent = Intent(context, Additem::class.java)
        context.startActivity(intent)

    }

}


inner class Personviewholder(view: View) : 
RecyclerView.ViewHolder(view) 
 {
    var personname: TextView = view.findViewById(R.id.tvname)
    var persondesc: TextView = view.findViewById(R.id.tvpersondesc)
    var personimg: ImageView = view.findViewById(R.id.imgperson)
    var layoutlist: LinearLayout = 
 view.findViewById(R.id.linearlayoutlist)
 }
 }

data class
data class Persons( var personname:String,
                var persondesc:String,
                var personimage:String)   


debug information
06/21 22:05:29: Launching 'app' on Pixel 3 API 30.
$ adb shell am start -n 
"com.a.recyclerview/com.a.recyclerview.LoginActivity" -a 
android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.a.recyclerview | 
com.a.recyclerview.test
Waiting for application to come online: com.a.recyclerview | 
com.a.recyclerview.test
Connecting to com.a.recyclerview
Capturing and displaying logcat messages from application. This 
behavior can be disabled in the "Logcat output" section of the 
"Debugger" settings page.
I/System.out: Debugger has connected
waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8602', transport: 
'socket'
I/chatty: uid=10155(com.a.recyclerview) identical 6 lines
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1337)
D/NetworkSecurityConfig: No Network Security Config specified, using 
 platform default
D/NetworkSecurityConfig: No Network Security Config specified, using 
platform default

I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT] I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation D/FirebaseAuth: Notifying id token listeners about user ( rwy6MpJLxYWyIAQbj2xFR0sRaRw2 ). I/FirebaseInitProvider: FirebaseApp initialization successful D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:51 and remote module com.google.android.gms.measurement.dynamite:51 Selected remote version of com.google.android.gms.measurement.dynamite, version >= 51 V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so W/.a.recyclervie: Accessing hidden method Landroid/view/View;- > computeFitSystemWindows(Landroid/graphics/Rt;Landroid/graphics /Rect;)Z

(greylist, reflection, allowed)
Accessing hidden method Landroid/view/ViewGroup;- 

makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) V/FA: onActivityCreated W/.a.recyclervie: Verification of android.content.pm.ApplicationInfo cn.a(java.lang.String, int) took 170.667ms (64.45 bytecodes/s) (984B approximate peak alloc) V/FA: App measurement collection enabled V/FA: App measurement enabled for app package, google app id: com.a.recyclerview, 1:14819963865:android:0fbd8c80422b89f216dfc8 I/FA: App measurement initialized, version: 42020 To enable debug logging run: adb shell setprop log.tag.FA VERBOSE I/FA: To enable faster debug mode event logging run: adb shell setprop debug.firebase.analytics.app com.a.recyclerview D/FA: Debug-level message logging enabled V/FA: onActivityCreated V/FA: Connecting to remote service D/HostConnection: HostConnection::get() New Host Connection established 0xf580da60, tid 7482 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_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without... D/EGL_emulation: eglCreateContext: 0xf580cb80: maj 3 min 0 rcv 3 D/EGL_emulation: eglMakeCurrent: 0xf580cb80: ver 3 0 (tinfo 0xc53c7b90) (first time) V/FA: Connection attempt already in progress I/Gralloc4: mapper 4.x is not supported D/HostConnection: createUnique: call D/HostConnection: HostConnection::get() New Host Connection established 0xf580dc20, tid 7482 D/goldfish-address-space: allocate: Ask for block of size 0x100 allocate: ioctl allocate returned offset 0x3fbc4d000 size 0x2000 V/FA: Connection attempt already in progress V/FA: Activity resumed, time: 3149571 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_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0 I/FA: Tag Manager is not found and thus will not be used V/FA: Connection attempt already in progress V/FA: Connection attempt already in progress I/OpenGLRenderer: Davey! duration=757ms; Flags=1, IntendedVsync=3149655912401, Vsync=3149722579065, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=3149736734700, AnimationStart=3149737212900, PerformTraversalsStart=3149737532500, DrawStart=3150142325100, SyncQueued=3150160621300, SyncStart=3150229754900, IssueDrawCommandsStart=3150230091100, SwapBuffers=3150464728600, FrameCompleted=3150482529700, DequeueBufferDuration=422700, QueueBufferDuration=1357200, GpuCompleted=72904454231491230, D/FA: Connected to remote service V/FA: Processing queued up service tasks: 5 I/.a.recyclervie: WaitForGcToComplete blocked RunEmptyCheckpoint on ProfileSaver for 5.416ms D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10155; state: ENABLED V/FA: Inactivity, disconnecting from the service

![](https://i.sstatic.net/WR6Pd.png)

Upvotes: 1

Views: 146

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

You're getting child("items") twice, so end up trying to read /Users/$uid/items/items, where no data exists.

To fix this, only specify child("items") once:

databaseReference = 
database?.reference!!.child("Users").child(auth.currentUser!!.uid).child("items")

databaseReference.addValueEventListener(object :ValueEventListener{
  ...

Upvotes: 0

Related Questions