Android Kotlin Для L oop запускается только один раз - PullRequest
0 голосов
/ 10 января 2020

У меня проблемы с моим адаптером просмотра переработчика. К нему добавляется только один элемент, добавляемый из для l oop, и я не могу понять, почему. Все мои операторы журнала указывают, что многие элементы предназначены для загрузки, но после однократного запуска загрузка прекращается.

вот мой журнал:

D/ChatRoomsListActivityTAG:: chatManager connected!
D/ChatRoomsListActivityTAG:: user: com.pusher.chatkit.CurrentUser@5f7cda6 is logged in to chatkit
D/ChatRoomsListActivityTAG:: joined rooms[Room(id=room 1577934249158, createdById=username1-PCKid, name=The Subtle Art of Not Giving a F*ck, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-02T03:04:10Z, updatedAt=2020-01-02T03:04:10Z, deletedAt=null), Room(id=my-room2, createdById=alice, name=my room2, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-01T20:48:29Z, updatedAt=2020-01-01T20:48:29Z, deletedAt=null), Room(id=room 1577934512686, createdById=username1-PCKid, name=The Subtle Art of Not Giving a F*ck, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-02T03:08:33Z, updatedAt=2020-01-02T03:08:33Z, deletedAt=null), Room(id=room 20200101-2041, createdById=username1-PCKid, name=The Subtle Art of Not Giving a F*ck, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-02T04:41:24Z, updatedAt=2020-01-02T04:41:24Z, deletedAt=null), Room(id=room 1577931826804, createdById=username1-PCKid, name=The Subtle Art of Not Giving a F*ck, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-02T02:23:48Z, updatedAt=2020-01-02T02:23:48Z, deletedAt=null), Room(id=room20200101-2045, createdById=username1-PCKid, name=The Subtle Art of Not Giving a F*ck, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-02T04:45:09Z, updatedAt=2020-01-02T04:45:09Z, deletedAt=null), Room(id=my-room, createdById=alice, name=my room, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=1, lastMessageAt=2020-01-10T05:44:08Z, createdAt=2020-01-01T20:44:39Z, updatedAt=2020-01-01T20:44:39Z, deletedAt=null)]
    joined rooms.size: 7
    adding room to adapter: Room(id=room 1577934249158, createdById=username1-PCKid, name=The Subtle Art of Not Giving a F*ck, pushNotificationTitleOverride=null, isPrivate=false, customData=null, unreadCount=0, lastMessageAt=null, createdAt=2020-01-02T03:04:10Z, updatedAt=2020-01-02T03:04:10Z, deletedAt=null)
    ForLoop .size:7

Вот мой код: ChatListRoomsActivity.kt

chatManager.connect(listeners = ChatListeners(

        )
                , callback = { result ->
            when (result) {
                is Result.Success -> {
                    // We have connected!
                    Log.d(AppActivityTags.chatRoomsListActivityTAG, "chatManager connected!")
                    val currentUser = result.value
                    AppController.currentUser = currentUser
                    Log.d(AppActivityTags.chatRoomsListActivityTAG, "user: " + currentUser + " is logged in to chatkit")

                    val userJoinedRooms = ArrayList<Room>(currentUser.rooms)
                    Log.d(AppActivityTags.chatRoomsListActivityTAG, "joined rooms" + userJoinedRooms.toString());
                    Log.d(AppActivityTags.chatRoomsListActivityTAG, "joined rooms.size: " + userJoinedRooms.size.toString());


                    for (i in 0 until userJoinedRooms.size) { //<-- issue happens in this for loop
                        Log.d(AppActivityTags.chatRoomsListActivityTAG, "adding room to adapter: " + userJoinedRooms[i].toString()) // <-- logged to console
                        Log.d(AppActivityTags.chatRoomsListActivityTAG, "ForLoop .size: " + userJoinedRooms.size)  // <-- logged to console

                        adapter.addRoom(userJoinedRooms[i]) // <-- only 1 room is added to the adapter. There should be 7.
                        Log.d(AppActivityTags.chatRoomsListActivityTAG, "adding room to adapter: " + userJoinedRooms[i].toString()) // <-- never logged to console

                    }

                    adapter.setInterface(object : ChatRoomsListAdapter.RoomClickedInterface {
                        override fun roomSelected(room: Room) {
                            if (room.memberUserIds.contains(currentUser.id)) {
                                // user already belongs to this room
                                roomJoined(room)
                                Log.d("roomSelected", "user already belongs to this room: " + roomJoined(room))
                            } else {
                                currentUser.joinRoom(
                                        roomId = room.id,
                                        callback = { result ->
                                            when (result) {
                                                is Result.Success -> {
                                                    // Joined the room!
                                                    roomJoined(result.value)
                                                }
                                                is Result.Failure -> {
                                                    Log.d("TAG", result.error.toString())
                                                }
                                            }
                                        }
                                )
                            }
                        }
                    })
                }

                is Result.Failure -> {
                    // Failure
                    Log.d(AppActivityTags.chatRoomsListActivityTAG, "ChatManager connection failed"
                            + result.error.toString())
                }
            }
        })

ChatListRoomsAdapter.kt

package com.example.android_myneighborsbookshelf.adapters

import Chatkit.AppController.Companion.currentUser
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.pusher.chatkit.rooms.Room
import android.view.LayoutInflater
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.android_myneighborsbookshelf.AppActivityTags
import com.example.android_myneighborsbookshelf.R


class ChatRoomsListAdapter: RecyclerView.Adapter<ChatRoomsListAdapter.ViewHolder>() {
    private var list = ArrayList<Room>()
    private var roomClickedInterface: RoomClickedInterface? = null


    fun addRoom(room:Room){ //<-- this function is what is called in the activity
        list.add(room)
        notifyDataSetChanged()
    }

    fun setInterface(roomClickedInterface:RoomClickedInterface){
        this.roomClickedInterface = roomClickedInterface
    }

    override fun getItemCount(): Int {
        return list.size
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(
                        R.layout.chatroom_list_row,
                        parent,
                        false
                )

        return ViewHolder(view)
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.roomName.text = list[position].name

    }

    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView), View.OnClickListener {
        override fun onClick(p0: View?) {
            roomClickedInterface?.roomSelected(list[adapterPosition])
            Toast.makeText(itemView.context, "item was clicked", Toast.LENGTH_LONG).show();

            Log.d(AppActivityTags.chatRoomsListAdapterTAG, "Size of adapter: " + list.size.toString())
            for (x in currentUser.rooms) {
                Log.d(AppActivityTags.chatRoomsListAdapterTAG, x.toString())
            }

        }

        var roomName: TextView = itemView.findViewById(android.R.id.text1)

        init {
            itemView.setOnClickListener(this)

        }
    }

    interface RoomClickedInterface{
        fun roomSelected(room:Room)
    }
}

1 Ответ

0 голосов
/ 10 января 2020

значение для l oop, которое вы используете, равно for (x in 0 until 10) println(x) // Prints 0 through 9 it will exclude 10, не используйте этот l oop, пока не хотите исключить какие-либо элементы, go через документы kotlin, прежде чем использовать что-либо, используйте userJoinedRooms.forEach { adapter.addRoom(it) }

Надеюсь, это работает

...