Retrieving data from firebase to android studio us

2019-03-03 18:23发布

问题:

how to get the id of data retrieved from the firebase so I can limit the data being retrieved from the firebase depending on the id.

here is my current code, it retrieves all the data from child "beetle" on my firebase database, I want to limit that so it will show only 1 data depending on what the id is.

    lateinit var listView: ListView
lateinit var ref: DatabaseReference
lateinit var beetleList:MutableList<Beetle>

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

    val capturedImage = intent.extras.getParcelable("captured_image") as Bitmap?
    val beetleName=intent.getStringExtra("Beetle")


    imageCaptured2.setImageBitmap(capturedImage)
    textBeetleName.setText(beetleName)

    listView = findViewById(R.id.beetle_list)
    beetleList = mutableListOf()
    ref = FirebaseDatabase.getInstance().getReference("beetle")

    ref.addValueEventListener(object : ValueEventListener{
        override fun onCancelled(p0: DatabaseError) {

        }

        override fun onDataChange(p0: DataSnapshot) {
            if(p0!!.exists()){
                beetleList.clear()
                for (e in p0.children){
                    val beetle = e.getValue(Beetle::class.java)
                    beetleList.add(beetle!!)
                }
                val adapter = BeetleCardAdapter(this@classify,R.layout.beetle_card_item,beetleList)
                listView.adapter = adapter
            }
        }
    })

here is my firebase structure:

firebase database

回答1:

You can visit Google Developer recommended training here Codelabs - Android

  • I filter Android category for you. You can find Web / Mobile quick training here or demo to follow along.

It is written on Java , but the idea is still there.

And you can quickly convert your code to Kotlin on Android Studio and study them later if your not familiar with Kotlin that much. From your Refactor menu (If I'm not mistaken for late version below 3.2.1).

.

.

From Firebase Docs don't forget to change the tab to Kotlin.

. If there is no Kotlin tab from the documentation, try the Firebase from your tool, and select the Realtime Database. It will show you the basic code. Since I'm using Java , it is showing Java code. Since your default lang is Kotlin, maybe it will show Kotlin code.

.

Kotlination - Firebase