Я разрабатываю приложение чата на kotlin для Android. Я делаю это для своих клиентов, чтобы они могли поговорить со мной. Я пытаюсь реализовать 2 метода извлечения пользователей, один из которых будет использоваться для извлечения моей учетной записи, а другой - для извлечения других учетных записей. Второй метод работает нормально, но приложение не получает мою учетную запись. Я использую Firebase API для базы данных.
ПРИМЕЧАНИЕ. Методы используются в упражнении «Новое сообщение».
KOTLIN
package com.eneluis.chat.messages
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.eneluis.chat.R
import com.eneluis.chat.models.User
import com.squareup.picasso.Picasso
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.Item
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.activity_new_message.*
import kotlinx.android.synthetic.main.user_row_new_message.view.*
class NewMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_message)
supportActionBar?.title = "Alege utilizatorul"
fetchEne()
fetchUsers()
}
companion object {
val USER_KEY = "USER_KEY"
}
private fun fetchEne() {
val Ene = FirebaseDatabase.getInstance().getReference("/users")
Ene.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val adapter = GroupAdapter<ViewHolder>()
p0.children.forEach {
Log.d("NewMessage", it.toString())
val user = it.getValue(User::class.java)
if (user != null) {
adapter.add(EneItem(user))
}
}
adapter.setOnItemClickListener { item, view ->
val EneItem = item as EneItem
val intent = Intent(view.context, ChatLogActivity::class.java)
// intent.putExtra(USER_KEY, userItem.user.username)
intent.putExtra(USER_KEY, EneItem.user)
startActivity(intent)
finish()
}
recyclerview_newmessage.adapter = adapter
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
private fun fetchUsers() {
val ref = FirebaseDatabase.getInstance().getReference("/useri")
ref.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val adapter = GroupAdapter<ViewHolder>()
p0.children.forEach {
Log.d("NewMessage", it.toString())
val user = it.getValue(User::class.java)
if (user != null) {
adapter.add(UserItem(user))
}
}
adapter.setOnItemClickListener { item, view ->
val userItem = item as UserItem
val intent = Intent(view.context, ChatLogActivity::class.java)
// intent.putExtra(USER_KEY, userItem.user.username)
intent.putExtra(USER_KEY, userItem.user)
startActivity(intent)
finish()
}
recyclerview_newmessage.adapter = adapter
}
override fun onCancelled(p0: DatabaseError) {
}
})
}
class EneItem(val user: User) : Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.username_textview_new_message.text = user.username
Picasso.get().load(user.profileImageUrl).into(viewHolder.itemView.imageview_new_message)
}
override fun getLayout(): Int {
return R.layout.user_row_new_message
}
}
class UserItem(val user: User) : Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.username_textview_new_message.text = user.username
Picasso.get().load(user.profileImageUrl).into(viewHolder.itemView.imageview_new_message)
}
override fun getLayout(): Int {
return R.layout.user_row_new_message
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="com.eneluis.chat.messages.NewMessageActivity">
<androidx.recyclerview.widget.RecyclerView
android:background="@android:color/holo_blue_light"
android:id="@+id/recyclerview_newmessage"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Firebase
chat-e4f05
useri
UENUzTa7QwNAPGYxZCx4xMZz4BG2
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"UENUzTa7QwNAPGYxZCx4xMZz4BG2"
username:
"hdhdhd"
Xi50i1c3D8VFZF4Nqqc9tls2wy92
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"Xi50i1c3D8VFZF4Nqqc9tls2wy92"
username:
"asd"
hVhX4VsGDpMu3v9NbgDRbRXYX703
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"hVhX4VsGDpMu3v9NbgDRbRXYX703"
username:
"fh"
rBuaTbfPk5TzFBYaTrA82At2vWM2
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"rBuaTbfPk5TzFBYaTrA82At2vWM2"
username:
"gdhdh"
vZZg7JeWweRV6Q8xKKalIB2quaB2
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"vZZg7JeWweRV6Q8xKKalIB2quaB2"
username:
"vfhf"
xPaRKjWsRRcwzpAXNIuBm4n9j1w2
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"xPaRKjWsRRcwzpAXNIuBm4n9j1w2"
username:
"br"
users
Q99f8rN2uRSflXMIi7diST75ba43
profileImageUrl:
"https://firebasestorage.googleapis.com/v0/b/cha..."
uid:
"Q99f8rN2uRSflXMIi7diST75ba43"
username:
"Ene Andrei"