Android Kotlin Pusher Chatkit - ошибка - Требуется членство в комнате - PullRequest
1 голос
/ 18 января 2020

Я пытаюсь интегрировать chatkit в мое Android приложение, собирающее части кода из этого учебного пособия по началу работы и этого android -publi c -demo-app проект на github, и я получаю эту ошибку:

D/ChatRoomsActivity: on subscripetoRoomMultipart reason:: Room membership required.

Пользователь уже является участником создаваемой комнаты. Это ошибка в соответствии с фрагментами панели управления / консоли, которые показаны в нижней части этого поста. В настоящее время текущий пользователь: user id=username2-PCKid

Ошибка возникает в ChatRoomAcitivity.kt при currentUser.subscribeToRoomMultipart. Я включил ChatRoomListActivity и адаптеры для контекста.

Любая помощь приветствуется. Пожалуйста, дайте мне знать, если требуется больше контекста.

вот мой ChatRoomListActivity.kt

class ChatRoomsListActivity : AppCompatActivity() {
    val adapter = ChatRoomsListAdapter();

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat_room_list)
        initRecyclerView()
        initChatManager()

    }

    private fun initRecyclerView() {

        recycler_view.layoutManager = LinearLayoutManager(this@ChatRoomsListActivity)
        recycler_view.adapter = adapter
    }

    private fun initChatManager() {
        val chatManager = ChatManager(
                instanceLocator = "************",
                userId = "username2-PCKid",
                dependencies = AndroidChatkitDependencies(
                        tokenProvider = ChatkitTokenProvider(
                                endpoint = "******************",
                                userId = "username2-PCKid"
                        )
                )
        )

        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>()

                    for (x in currentUser.rooms) {
                            adapter.addRoom(x)
                            recycler_view.smoothScrollToPosition(0)
                    }

                    adapter.notifyDataSetChanged()

                    Log.d(AppActivityTags.chatRoomsListActivityTAG, "joined rooms.size: " + userJoinedRooms.size.toString());

                    adapter.setInterface(object : ChatRoomsListAdapter.RoomClickedInterface {

                        override fun roomSelected(room: Room) {
                            Log.d(AppActivityTags.chatRoomsListActivityTAG, "Room clicked!")
                            if (room.memberUserIds.contains("username2-PCKid")) {
//                            if (room.memberUserIds.contains(currentUser.id)) { <-- OG code
                                // 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(AppActivityTags.chatRoomsListActivityTAG, result.error.toString())
                                                }
                                            }
                                        }
                                )
                            }
                        }
                    })
                }

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

    }

    private fun roomJoined(room: Room) {
        val intent = Intent(this@ChatRoomsListActivity, ChatRoomActivity::class.java)
        Log.d(AppActivityTags.chatRoomsListActivityTAG, "function roomJoined activated")
        intent.putExtra("room_id", room.id)
        intent.putExtra("room_name", room.name)
        startActivity(intent)
    }
}

вот мой ChatRoomListAdapter.kt

class ChatRoomsListAdapter: RecyclerView.Adapter<ChatRoomsListAdapter.ViewHolder>() {

    private var list = ArrayList<Room>()
    private var roomClickedInterface: RoomClickedInterface? = null

    fun addRoom(room:Room){

        list.add(room);
        Log.d(AppActivityTags.chatRoomsListAdapterTAG, "Room name: " + room.name)
        Log.d(AppActivityTags.chatRoomsListAdapterTAG, "Room id: " + room.id)
        Log.d(AppActivityTags.chatRoomsListAdapterTAG, "Room memberUserIds: " + room.memberUserIds)
        Log.d(AppActivityTags.chatRoomsListAdapterTAG, "Room isPrivate: " + room.isPrivate)
    }


    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(
                        android.R.layout.simple_list_item_1,
                        parent,
                        false
                )

        return ViewHolder(view)
    }

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


        holder.itemView.setOnClickListener {

            room = list[position]

            val intent = Intent(context, ChatRoomActivity::class.java)
            Log.d(AppActivityTags.chatRoomsListActivityTAG, "function roomJoined activated")
            intent.putExtra("room_id", room.id)
            intent.putExtra("room_name", room.name)
            context.startActivity(intent)
        }
    }


    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()

            val mContext = itemView.context
            Log.d(AppActivityTags.chatRoomsListAdapterTAG, "Size of adapter: " + list.size.toString())
            Log.d(AppActivityTags.chatRoomsListAdapterTAG, roomName.toString() + " roomName clicked")

        }

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

        init {
            itemView.setOnClickListener(this)

        }
    }

    interface RoomClickedInterface{
        fun roomSelected(room:Room)

    }
}

вот мой ChatRoomActivity.kt

class ChatRoomActivity : AppCompatActivity() {
    lateinit var adapter:ChatRoomAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat_room)
        supportActionBar!!.title = intent.getStringExtra("room_name")
        adapter = ChatRoomAdapter()
        setUpRecyclerView()

        val currentUser = AppController.currentUser
        val roomId = intent.getStringExtra("room_id")

        currentUser.subscribeToRoomMultipart(
                roomId = roomId,
                listeners = RoomListeners(
                        onMultipartMessage = { message ->
                            Log.d("TAG",message.toString())
                            // com.pusher.chatkit.messages.multipart.Message

                            runOnUiThread(Runnable{
                                adapter.addMessage(message)
                                recycler_view.layoutManager?.scrollToPosition(adapter.itemCount -1)

                            })


                        },
                        onErrorOccurred = { error ->
                            Log.d(AppActivityTags.chatRoomActivityTAG, "error.reason: " + error.reason)
                            Log.d(AppActivityTags.chatRoomActivityTAG, "currentuser.rooms: " + currentUser.rooms)

                        }
                ),
                messageLimit = 100, // Optional
                callback = { subscription ->
                    // Called when the subscription has started.
                    // You should terminate the subscription with subscription.unsubscribe()
                    // when it is no longer needed
                }
        )

        button_send.setOnClickListener {
            if (edit_text.text.isNotEmpty()){
                currentUser.sendSimpleMessage(
                        roomId = roomId,
                        messageText = edit_text.text.toString(),
                        callback = { result -> //Result<Int, Error>
                            when (result) {

                                is Result.Success -> {
                                    runOnUiThread {
                                        edit_text.text.clear()
                                        hideKeyboard()
                                    }
                                }
                                is Result.Failure -> {
                                    Log.d(AppActivityTags.chatRoomActivityTAG, "error @ button_send.setOnclick: " + result.error.toString())
                                }
                            }
                        }
                )
            }
        }
    }

    private fun hideKeyboard() {
        val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        var view = this.currentFocus

        if (view == null) {
            view = View(this)
        }

        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    private fun setUpRecyclerView() {
        recycler_view.layoutManager= LinearLayoutManager(this@ChatRoomActivity)
        recycler_view.adapter = adapter
    }
}

вот мой ChatRoomAdapter.kt

class ChatRoomAdapter: RecyclerView.Adapter<ChatRoomAdapter.ViewHolder>() {
    private var list = ArrayList<Message>()


    fun addMessage(message: Message){
        list.add(message)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.custom_chat_row,parent,false)

        return ViewHolder(view)
    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {

        val inlineMessage: Payload.Inline = list[position].parts[0].payload as Payload.Inline
        holder.userName.text = list[position].sender.name
        holder.message.text = inlineMessage.content

    }


    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        var userName: TextView = itemView.findViewById(R.id.text_user_name)
        var message: TextView = itemView.findViewById(R.id.chat_message)

    }
}

enter image description here

enter image description here

1 Ответ

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

Мне кажется, я знаю, что случилось.

Я думаю, что случилось то, что я создал комнату из панели инструментов набора чата, а затем попытался войти как они. и затем войдите в комнату как они. Я мог видеть свои списки чатов, с которыми они были связаны, однако я думаю, что, поскольку я создал чат с помощью панели инструментов, мне показалось, что я был кем-то другим.

Короче говоря, это работает, если я создаю комнату из моего android эмулятора и затем go в комнату. если я создаю комнату из приборной панели и пытаюсь присоединиться, она, похоже, не работает.

...