не удалось извлечь данные из базы данных firebase firestore в recyclerview

# #android #firebase #kotlin #google-cloud-firestore

Вопрос:

Я работаю на приложение, где пользователь вошел внимание хранится в базе данных firestore, а также вам представил в переработчик вид внутри приложения все работает хорошо с firestore ……….все вошли ноты правильно хранятся в базе данных firestore, но когда я выборки данных в Recycler view приложение показывает пустой вид переработчик……..приложение не сбой и все другие функции работают правильно, проблема связана с основной деятельностью только всех других видов деятельности, работают корректно **основной вид деятельности **

 class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {
    //Variables
    private lateinit var drawerLayout : DrawerLayout
    lateinit var toggle : ActionBarDrawerToggle
    lateinit var navView : NavigationView
    lateinit var toolBar : androidx.appcompat.widget.Toolbar
    lateinit var fStore : FirebaseFirestore
    private var adapter: NotesRecyclerAdapter? = null

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

        // toolbar support
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        fStore = FirebaseFirestore.getInstance()
        presentNotes()
        // creating layout manager
        val layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        //intiializing

        drawerLayout = drawer
        navView = navigation_view
        toolBar = toolbar

        // navView button click managed
        navView.setNavigationItemSelectedListener(this)
        toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close)
        toggle.isDrawerIndicatorEnabled = true
        toggle.syncState()

    }
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.addBtn -> {
                val intent : Intent = Intent(this,AddNotes::class.java)
                startActivity(intent)
            }
            else->{
                Toast.makeText(this,"ButtonClicked",Toast.LENGTH_LONG).show()
            }
        }

        return false
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.option_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId == R.id.settings){
            Toast.makeText(this,"Setting selected",Toast.LENGTH_LONG).show()
        }
        return super.onOptionsItemSelected(item)
    }

    //clicks Managed
    fun noteItemClicked(titles: String, content: String) {
        Toast.makeText(this, "Item Clicked" , Toast.LENGTH_SHORT).show()
    }

    fun fabBtnClicked(view : View){
        startActivity(Intent(this,AddNotes::class.java))
    }

    private fun presentNotes(){
        val query = fStore.collection("products").orderBy("title", Query.Direction.ASCENDING)
        val myNotes = FirestoreRecyclerOptions.Builder<Notes>().setQuery(query, Notes::class.java).build()
        adapter = NotesRecyclerAdapter(myNotes)

    }
    private inner class NoteViewHolder internal constructor(val view: View) : RecyclerView.ViewHolder(view) {
        val content : TextView = view.content
        val titles : TextView = view.titles
    }
    private inner class NotesRecyclerAdapter(allNotes: FirestoreRecyclerOptions<Notes>) : FirestoreRecyclerAdapter<Notes, NoteViewHolder>(allNotes) {

        override fun onBindViewHolder(noteViewHolder: NoteViewHolder, position: Int, notes: Notes) {
            val currentTitle = notes.title?.get(position)
            val currentContent = notes.content?.get(position)
            noteViewHolder.content.text = currentContent.toString()
            noteViewHolder.titles.text = currentTitle.toString()
            noteViewHolder.view.setOnClickListener {
                val intent : Intent = Intent(noteViewHolder.view.context,NotesDeatils::class.java)
                intent.putExtra("Title" , currentTitle)
                intent.putExtra("Content",currentContent)
                noteViewHolder.view.context.startActivity(intent)
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.single_note_view, parent, false)
            return NoteViewHolder(view)
        }
    }

    override fun onStart() {
        super.onStart()
        adapter!!.startListening()
    }

    override fun onStop() {
        super.onStop()
        if(adapter!= null){
            adapter!!.stopListening()
        }

    }
}
 

Правила пожарной безопасности

 rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}
 

Скриншот базы данных Firestore

Класс заметок

 data class  Notes(var title : String?,
                 var content : String?)
 

Logcat

 2021-07-07 00:10:39.892 32024-32024/? I/zygote64: Late-enabling -Xcheck:jni
2021-07-07 00:10:39.914 32024-32024/? W/zygote64: miui_dex2oat: DeoptimizeBootImage: patch entry points of methods in boot image to interpreter bridge
2021-07-07 00:10:40.365 32024-32024/com.example.mynotes W/zygote64: miui_dex2oat: OatFile: /data/app/com.example.mynotes-EEu6hI141xt5_EuEFT3oBg==/oat/arm64/base.odex Compiler-Filter = quicken
2021-07-07 00:10:40.370 32024-32024/com.example.mynotes W/ResourceType: No package identifier when getting name for resource number 0x00000000
2021-07-07 00:10:40.544 32024-32024/com.example.mynotes I/MultiDex: VM with version 2.1.0 has multidex support
2021-07-07 00:10:40.545 32024-32024/com.example.mynotes I/MultiDex: Installing application
2021-07-07 00:10:40.545 32024-32024/com.example.mynotes I/MultiDex: VM has multidex support, MultiDex support library is disabled.
2021-07-07 00:10:40.592 32024-32024/com.example.mynotes I/FirebaseApp: Device unlocked: initializing all Firebase APIs for app [DEFAULT]
2021-07-07 00:10:40.678 32024-32024/com.example.mynotes I/FirebaseInitProvider: FirebaseApp initialization successful
2021-07-07 00:10:40.740 32024-32024/com.example.mynotes W/ResourceType: No package identifier when getting name for resource number 0x00000000
2021-07-07 00:10:40.763 32024-32065/com.example.mynotes W/zygote64: Unsupported class loader
2021-07-07 00:10:40.764 32024-32024/com.example.mynotes W/ResourceType: No package identifier when getting name for resource number 0x00000000
2021-07-07 00:10:40.774 32024-32070/com.example.mynotes I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to fallback implementation
2021-07-07 00:10:40.780 32024-32024/com.example.mynotes W/ResourceType: No package identifier when getting name for resource number 0x00000000
2021-07-07 00:10:40.788 32024-32065/com.example.mynotes W/zygote64: Skipping duplicate class check due to unsupported classloader
2021-07-07 00:10:40.788 32024-32065/com.example.mynotes W/zygote64: miui_dex2oat: OatFile: /data/user_de/0/com.google.android.gms/app_chimera/m/000001dd/oat/arm64/DynamiteLoader.odex Compiler-Filter = speed
2021-07-07 00:10:40.801 32024-32065/com.example.mynotes I/DynamiteModule: Considering local module com.google.android.gms.measurement.dynamite:51 and remote module com.google.android.gms.measurement.dynamite:51
2021-07-07 00:10:40.801 32024-32065/com.example.mynotes I/DynamiteModule: Selected remote version of com.google.android.gms.measurement.dynamite, version >= 51
2021-07-07 00:10:40.802 32024-32065/com.example.mynotes V/DynamiteModule: Dynamite loader version >= 2, using loadModule2NoCrashUtils
2021-07-07 00:10:40.844 32024-32024/com.example.mynotes D/AccessibilityManager: AccessibilityManager status: mPackageName = com.example.mynotes, mOptimizeEnabled = true, mIsEnabled = false, mIsUiAutomationEnabled = false, mIsInterestedPackage =false
2021-07-07 00:10:40.927 32024-32065/com.example.mynotes W/ResourceType: No package identifier when getting name for resource number 0x00000000
2021-07-07 00:10:40.931 32024-32065/com.example.mynotes W/ResourceType: ResTable_typeSpec entry count inconsistent: given 67, previously 69
2021-07-07 00:10:40.974 32024-32065/com.example.mynotes W/zygote64: Unsupported class loader
2021-07-07 00:10:40.981 32024-32024/com.example.mynotes I/FloatingActionButton: Setting a custom background is not supported.
2021-07-07 00:10:40.984 32024-32065/com.example.mynotes W/zygote64: Skipping duplicate class check due to unsupported classloader
2021-07-07 00:10:40.985 32024-32065/com.example.mynotes W/zygote64: miui_dex2oat: OatFile: /data/user_de/0/com.google.android.gms/app_chimera/m/000001e2/oat/arm64/MeasurementDynamite.odex Compiler-Filter = speed-profile
2021-07-07 00:10:40.990 32024-32065/com.example.mynotes W/ResourceType: No package identifier when getting name for resource number 0x00000000
2021-07-07 00:10:41.059 32024-32065/com.example.mynotes V/FA: onActivityCreated
2021-07-07 00:10:41.544 32024-32132/com.example.mynotes W/DynamiteModule: Local module descriptor class for providerinstaller not found.
2021-07-07 00:10:41.583 32024-32100/com.example.mynotes V/FA: App measurement collection enabled
2021-07-07 00:10:41.584 32024-32100/com.example.mynotes V/FA: App measurement enabled for app package, google app id: com.example.mynotes, 1:611508760900:android:377e32489b07020e4ce711
2021-07-07 00:10:41.589 32024-32100/com.example.mynotes I/FA: App measurement initialized, version: 42020
2021-07-07 00:10:41.589 32024-32100/com.example.mynotes I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
2021-07-07 00:10:41.590 32024-32100/com.example.mynotes I/FA: To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app com.example.mynotes
2021-07-07 00:10:41.591 32024-32100/com.example.mynotes D/FA: Debug-level message logging enabled
2021-07-07 00:10:41.602 32024-32135/com.example.mynotes D/OpenGLRenderer: HWUI GL Pipeline
2021-07-07 00:10:41.614 32024-32132/com.example.mynotes I/DynamiteModule: Considering local module providerinstaller:0 and remote module providerinstaller:0
2021-07-07 00:10:41.622 32024-32132/com.example.mynotes W/ProviderInstaller: Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
2021-07-07 00:10:41.932 32024-32132/com.example.mynotes W/zygote64: miui_dex2oat: oat file of /system/framework/com.android.media.remotedisplay.jar is not exists
2021-07-07 00:10:41.933 32024-32132/com.example.mynotes W/zygote64: miui_dex2oat: /system/framework/com.android.media.remotedisplay.jar: Fall back to running out of the original dex file.
2021-07-07 00:10:41.935 32024-32132/com.example.mynotes W/zygote64: miui_dex2oat: oat file of /system/framework/com.android.location.provider.jar is not exists
2021-07-07 00:10:41.936 32024-32132/com.example.mynotes W/zygote64: miui_dex2oat: /system/framework/com.android.location.provider.jar: Fall back to running out of the original dex file.
2021-07-07 00:10:41.977 32024-32135/com.example.mynotes I/Adreno: QUALCOMM build                   : 8e3df98, Ie4790512f3
    Build Date                       : 04/11/18
    OpenGL ES Shader Compiler Version: EV031.22.00.01
    Local Branch                     : 
    Remote Branch                    : quic/gfx-adreno.lnx.1.0.r36-rel
    Remote Branch                    : NONE
    Reconstruct Branch               : NOTHING
2021-07-07 00:10:41.981 32024-32135/com.example.mynotes D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8953.so from current namespace instead of sphal namespace.
2021-07-07 00:10:42.001 32024-32132/com.example.mynotes W/zygote64: miui_dex2oat: OatFile: /data/app/com.google.android.gms-4IsMf_nEL9lL94jcrgN15g==/oat/arm64/base.odex Compiler-Filter = speed
2021-07-07 00:10:42.001 32024-32135/com.example.mynotes I/Adreno: PFP: 0x005ff087, ME: 0x005ff063
2021-07-07 00:10:42.004 32024-32132/com.example.mynotes W/zygote64: miui_dex2oat: oat file of /data/app/com.google.android.gms-4IsMf_nEL9lL94jcrgN15g==/split_config.en.apk is not exists
2021-07-07 00:10:42.009 32024-32135/com.example.mynotes I/zygote64: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
2021-07-07 00:10:42.011 32024-32135/com.example.mynotes I/OpenGLRenderer: Initialized EGL, version 1.4
2021-07-07 00:10:42.011 32024-32135/com.example.mynotes D/OpenGLRenderer: Swap behavior 2
2021-07-07 00:10:42.047 32024-32100/com.example.mynotes V/FA: Connecting to remote service
2021-07-07 00:10:42.141 32024-32132/com.example.mynotes V/NativeCrypto: Registering com/google/android/gms/org/conscrypt/NativeCrypto's 294 native methods...
2021-07-07 00:10:42.176 32024-32100/com.example.mynotes V/FA: Connection attempt already in progress
2021-07-07 00:10:42.208 32024-32100/com.example.mynotes V/FA: Connection attempt already in progress
2021-07-07 00:10:42.209 32024-32100/com.example.mynotes V/FA: Activity resumed, time: 234182424
2021-07-07 00:10:42.237 32024-32100/com.example.mynotes I/FA: Tag Manager is not found and thus will not be used
2021-07-07 00:10:42.239 32024-32029/com.example.mynotes I/zygote64: Do partial code cache collection, code=29KB, data=25KB
2021-07-07 00:10:42.239 32024-32029/com.example.mynotes I/zygote64: After code cache collection, code=29KB, data=25KB
2021-07-07 00:10:42.239 32024-32029/com.example.mynotes I/zygote64: Increasing code cache capacity to 128KB
2021-07-07 00:10:42.268 32024-32024/com.example.mynotes W/Looper: Slow Frame: doFrame is 344ms late
2021-07-07 00:10:42.306 32024-32135/com.example.mynotes D/vndksupport: Loading /vendor/lib64/hw/android.hardware.graphics.mapper@2.0-impl.so from current namespace instead of sphal namespace.
2021-07-07 00:10:42.307 32024-32135/com.example.mynotes D/vndksupport: Loading /vendor/lib64/hw/gralloc.msm8953.so from current namespace instead of sphal namespace.
2021-07-07 00:10:42.345 32024-32100/com.example.mynotes V/FA: Connection attempt already in progress
2021-07-07 00:10:42.346 32024-32132/com.example.mynotes D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2021-07-07 00:10:42.353 32024-32100/com.example.mynotes V/FA: Connection attempt already in progress
2021-07-07 00:10:42.368 32024-32132/com.example.mynotes I/ProviderInstaller: Installed default security provider GmsCore_OpenSSL
2021-07-07 00:10:42.728 32024-32100/com.example.mynotes D/FA: Connected to remote service
2021-07-07 00:10:42.731 32024-32100/com.example.mynotes V/FA: Processing queued up service tasks: 5
 

activity_main

 <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NotesDeatils">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/Theme.MyNotes.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@ id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/teal_700"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
            app:popupTheme="@style/Theme.MyNotes.PopupOverlay" >
            <TextView
                android:id="@ id/notesDetailTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="TextView"
                android:textColor="@color/white"
                android:textStyle="bold"
                android:textSize="16sp"/>
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_notes_deatils" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@ id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
 

content_main

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.appcompat.widget.Toolbar
        android:id="@ id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/teal_700"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@ id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/toolbar" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@ id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:maxImageSize="30dp"
        android:background="@color/white"
        app:srcCompat="@drawable/ic_baseline_add_24"
        tools:ignore="VectorDrawableCompat"
        android:onClick="fabBtnClicked"

       />
</androidx.constraintlayout.widget.ConstraintLayout>
 

ссылка
на github Примечаниеapp Ссылка на Github

Комментарии:

1. Я не уверен, что понимаю. Что именно в этом коде работает не так, как вы ожидаете?

2. Я ожидаю получить данные из базы данных firestore и отобразить их в представлении recycler , но представление recycler все время пустое, извлеченные данные не отображаются в представлении recycler

3. notes.title?.get(position) Возвращает ли оно правильное значение?

4. Как проверить, дает ли он правильное значение или нет??

5. Просто добавив Log.d("TAG", notes.title?.get(position)) параметр состояния журнала .

Ответ №1:

Вот ответ на мой вопрос, я получал данные неправильным образом

 class MainActivity : AppCompatActivity(),NavigationView.OnNavigationItemSelectedListener {
    //Variables
    private lateinit var drawerLayout : DrawerLayout
    lateinit var toggle : ActionBarDrawerToggle
    lateinit var navView : NavigationView
    lateinit var toolBar : androidx.appcompat.widget.Toolbar
    lateinit var fStore : FirebaseFirestore
    //onCreate fun
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // toolbar support
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        fStore = FirebaseFirestore.getInstance()
        val query = fStore.collection("notes").orderBy("title",Query.Direction.DESCENDING)
        val myNotes = FirestoreRecyclerOptions.Builder<Notes>().setQuery(query, Notes::class.java).setLifecycleOwner(this).build()
        val adapter = object : FirestoreRecyclerAdapter<Notes, NoteViewHolder>(myNotes){
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
                val view = LayoutInflater.from(this@MainActivity).inflate(R.layout.single_note_view,parent,false)
                return NoteViewHolder(view)
            }

            override fun onBindViewHolder(holder: NoteViewHolder, p1: Int, note: Notes) {
                holder.content.text = note.title
                holder.titles.text = note.content
                holder.view.setOnClickListener {
                    val intent : Intent = Intent(holder.view.context,NotesDeatils::class.java)
                    intent.putExtra("Title" , note.title)
                    intent.putExtra("Content",note.content)
                    holder.view.context.startActivity(intent)
                }
            }

        }
        // creating layout manager
        val layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = layoutManager

        //intiializing

        drawerLayout = drawer
        navView = navigation_view
        toolBar = toolbar

        // navView button click managed
        navView.setNavigationItemSelectedListener(this)
        toggle = ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open,R.string.close)
        toggle.isDrawerIndicatorEnabled = true
        toggle.syncState()

    }
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.addBtn -> {
                val intent : Intent = Intent(this,AddNotes::class.java)
                startActivity(intent)
            }
            else->{
                Toast.makeText(this,"ButtonClicked",Toast.LENGTH_LONG).show()
            }
        }

        return false
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.option_menu,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId == R.id.settings){
            Toast.makeText(this,"Setting selected",Toast.LENGTH_LONG).show()
        }
        return super.onOptionsItemSelected(item)
    }

    //clicks Managed
    fun noteItemClicked(titles: String, content: String) {
        Toast.makeText(this, "Item Clicked" , Toast.LENGTH_SHORT).show()
    }

    fun fabBtnClicked(view : View){
        startActivity(Intent(this,AddNotes::class.java))
    }

    private inner class NoteViewHolder internal constructor(val view: View) : RecyclerView.ViewHolder(view) {
        val content : TextView = view.content
        val titles : TextView = view.titles

    }


}