I've the below code that was working fine with RecyclerView
, in the same time, I've a websocket
that works for onMessage
and print the received msg correctly.
Then I tried to merge them together, i.e. receive data from socket
and push it directly to the RecyclerView
but it is not showing anything in RecyclerView
screen
During one of my trials, I got this error:
I/Websocket: Error Only the original thread that created a view hierarchy can touch its views.
lateinit var mWebSocketClient: WebSocketClient
lateinit var uniqueID: String
lateinit var rv: RecyclerView
val chaptersList: ArrayList<String> = ArrayList()
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rv = rvChapterList // "@+id/rvChapterList" of RecyclerView
// chaptersList.add(s)
// rvChapterList.layoutManager = layoutManager
// rvChapterList.adapter = ChapterAdapter(this, chaptersList)
var context= this
connectWebSocket(context)
}
fun connectWebSocket(context: MainActivity) {
val uri: URI
try {
uri = URI("ws://10.0.2.2:8080/ws")
} catch (e: URISyntaxException) {
e.printStackTrace()
println("ws faild")
return
}
mWebSocketClient = object : WebSocketClient(uri) {
override fun onOpen(serverHandshake: ServerHandshake) {
Log.i("Websocket", "Opened")
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL)
}
override fun onMessage(s: String) {
Log.i("Websocket", "Recieved $s") // This is working
chaptersList.add(s)
Log.i("chaptersList", "chaptersList $s") // This is working
rv.layoutManager = LinearLayoutManager(context)
rv.adapter = ChapterAdapter(context , chaptersList) // This is not working
}
}
mWebSocketClient.connect()
}
UPDATE
Referring to this answer, I tried the below, but it did not work:
lateinit var rv: RecyclerView
lateinit var layoutManager: RecyclerView.LayoutManager
lateinit var adaptor: ChapterAdapter
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
layoutManager = LinearLayoutManager(this)
rv = rvChapterList
adaptor = ChapterAdapter(this, chaptersList)
rv.adapter = adaptor
rv.layoutManager = layoutManager
rv.adapter = ChapterAdapter(this, chaptersList)
}
}
fun connectWebSocket(context: MainActivity) {
override fun onMessage(s: String) {
val insertIndex = chaptersList.size
chaptersList.add(insertIndex, s)
adaptor.notifyItemInserted(insertIndex)
adaptor.notifyDataSetChanged()
}
}