Я пытаюсь отобразить сообщения, которые пользователь отправляет в базу данных Firebase в реальном времени, используя представление Recyler в Android, но мой экран чата отображает пустой экран, даже когда база данных Firebase обновляется.
это файл MainChatActivity.kt
class MainChatActivity : AppCompatActivity() {
var mDisplayName:String?=null
var databaseref:DatabaseReference?=null
var msgEditText:EditText?=null
var sendButton:ImageButton?=null
var msgRow:RecyclerView?=null
var Adapter:Adapter?=null
var viewManager: RecyclerView.LayoutManager?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_chat)
msgEditText = findViewById(R.id.messageInput)
sendButton=findViewById(R.id.sendButton)
msgRow=findViewById<RecyclerView>(R.id.chat_list_view)
Adapter = Adapter(databaseref,mDisplayName,this@MainChatActivity)
viewManager = LinearLayoutManager(this@MainChatActivity)
msgRow?.apply {
layoutManager=viewManager
adapter=Adapter
itemAnimator=DefaultItemAnimator()
}
}
override fun onResume() {
super.onResume()
databaseref=FirebaseDatabase.getInstance().getReference()
msgEditText?.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
sendMessage(msgEditText?.text.toString())
true
})
sendButton?.setOnClickListener {
sendMessage(msgEditText?.text.toString())
}
}
private fun sendMessage(message: String) {
if (message != "") {
val prefs: SharedPreferences = this@MainChatActivity.getSharedPreferences(RegisterActivity.static.myPrefs, 0)
mDisplayName=prefs.getString("DisaplayName","DisaplayName")
Log.v("displaynamechat",mDisplayName.toString())
if(prefs.getString("DisaplayName",null) =="")
{
mDisplayName="Anonymous"
}
val chat = Messages(message, mDisplayName.toString())
databaseref?.child("messages")?.push()?.setValue(chat)
msgEditText?.setText("")
}
}
public override fun onStart() {
super.onStart()
}
override fun onStop() {
super.onStop()
Adapter?.cleanup()
}
}
это файл Adapter.kt, который я использую для представления переработчика
class Adapter (databaseRef: DatabaseReference?, displayName: String?, context: Context): RecyclerView.Adapter<Adapter.viewHolder>(){
var databaseRef:DatabaseReference?=null
var author:String?=null
var context:Context?=null
lateinit var dataSnap:ArrayList<DataSnapshot>
private val mListener = object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {
dataSnap.add(dataSnapshot)
notifyDataSetChanged()
}
override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) {
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {
}
override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) {
}
override fun onCancelled(databaseError: DatabaseError) {
}
}
init {
this.databaseRef=databaseRef?.child("messages")
this.author=displayName
this.context=context
this.dataSnap = java.util.ArrayList<DataSnapshot>()
this.databaseRef?.addChildEventListener(this.mListener)
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): viewHolder {
var itemvew= LayoutInflater.from(p0.context)
.inflate(R.layout.chat_msg_row,p0,false)
return viewHolder(itemvew)
}
override fun getItemCount(): Int {
return dataSnap.size
}
override fun onBindViewHolder(p0: viewHolder, p1: Int) {
var gettingcurrentSnap= dataSnap.get(p0.adapterPosition)
var meessageClass = gettingcurrentSnap.getValue(Messages::class.java)
Log.v("flashchat message",meessageClass?.msg)
p0.msgText?.setText(meessageClass?.msg)
if(author =="")
author="Anonymous"
p0.author?.setText(meessageClass?.author)
if (meessageClass?.author == author) {
p0.body?.setBackgroundResource(R.drawable.bubble2)
p0.body?.gravity = Gravity.END
p0.author?.setTextColor(Color.GREEN)
}
else
{
p0.body?.setBackgroundResource(R.drawable.bubble1)
p0.body?.gravity = Gravity.START
p0.author?.setTextColor(Color.BLUE)
}
}
class viewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var msgText: TextView?=null
var author: TextView?=null
var body:LinearLayout?=null
init {
msgText=itemView.findViewById(R.id.message)
author=itemView.findViewById(R.id.author)
body=itemView.findViewById(R.id.singleMessageContainer)
}
}
internal fun cleanup() {
databaseRef?.removeEventListener(mListener)
}
}
это класс для хранения сообщений из datasnapshot из firebase Messages.kt class
class Messages {
var author: String=""
var msg: String=""
private constructor() {}
constructor(author: String, text: String) {
this.author = author
this.msg = text
}
}
activity_main_chat.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/light_purple">
<android.support.v7.widget.RecyclerView
android:id="@+id/chat_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/listFooter"
android:layout_alignParentTop="true"
android:divider="@null"
android:dividerHeight="0dp"
android:transcriptMode="alwaysScroll" />
<LinearLayout
android:id="@+id/listFooter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="bottom">
<EditText
android:id="@+id/messageInput"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textColor="@color/black"
android:textColorHint="@color/black"
android:hint="@string/prompt_msg"
android:imeActionLabel="@string/action_send"
android:imeOptions="actionUnspecified"
android:inputType="textCapSentences|textAutoCorrect"
android:maxLines="1"
android:gravity="center_horizontal"/>
<ImageButton
android:id="@+id/sendButton"
android:padding="10dp"
android:background="@drawable/circle_shape"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_menu_send"
android:contentDescription="@string/action_send"/>
</LinearLayout>
</RelativeLayout>
chat_msg_row.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/singleMessageContainer"
android:orientation="vertical">
<TextView
android:id="@+id/author"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_gravity="start"
android:textColor="@color/green"
android:gravity="center_vertical"
android:textSize="15sp"
android:textStyle="bold"
android:text="@string/prompt_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message"
android:layout_gravity="start"
android:gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:padding="10dp"
android:textSize="15sp"
android:text="@string/sample_message"
android:textColor="@android:color/primary_text_light"
/>
</LinearLayout>