(7)에서 빠져있는 부분들은 아래와 같이 변환해준다.
위와 같이 구현하면된다. 그리고 이제 ChatModel을 추가하자.
또한 NotificationModel 도 추가해준다.
이제 드디어 RecyclerView를 구현해주자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
|
inner class ChatRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val requestOptions = RequestOptions().transforms(CenterCrop(), RoundedCorners(90))
internal var messageList: MutableList<Message>? = null
private var beforeDay: String? = null
internal var beforeViewHolder: MessageViewHolder? = null
fun startListening() {
beforeDay = null
messageList?.clear()
val roomRef: CollectionReference? =
firestore?.collection("rooms")?.document(roomID!!)?.collection("messages")
// my chatting room information
listenerRegistration = roomRef?.orderBy("timestamp")?.addSnapshotListener { p0, e ->
if (e != null) {
return@addSnapshotListener
}
var message: Message
for (change in p0!!.documentChanges) {
when (change.type) {
message = change.document.toObject<Message>(Message::class.java)
if (message.readUsers.indexOf(myUid) == -1) {
message.readUsers.add(myUid)
change.document.reference
.update("readUsers", message.getReadUsers())
}
messageList?.add(message)
notifyItemInserted(change.newIndex)
}
Type.MODIFIED -> {
message = change.document.toObject<Message>(
Message::class.java
)
messageList?.set(change.oldIndex, message)
notifyItemChanged(change.oldIndex)
}
Type.REMOVED -> {
messageList?.removeAt(change.oldIndex)
notifyItemRemoved(change.oldIndex)
}
}
}
recyclerView?.scrollToPosition(messageList!!.size - 1)
}
}
fun stopListening() {
if (listenerRegistration != null) {
listenerRegistration?.remove()
listenerRegistration = null
}
messageList?.clear()
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
val message: Message = messageList!![position]
when (message.msgtype) {
"1" -> R.layout.item_chatimage_right
"2" -> R.layout.item_chatfile_right
else -> R.layout.item_chatmsg_right
}
} else {
when (message.getMsgtype()) {
"1" -> R.layout.item_chatimage_left
"2" -> R.layout.item_chatfile_left
else -> R.layout.item_chatmsg_left
}
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
var view: View? = null
.inflate(viewType, parent, false)
return MessageViewHolder(view)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val messageViewHolder: ChatFragment.MessageViewHolder =
holder as ChatFragment.MessageViewHolder
val message: Message = messageList!![position]
setReadCounter(message, messageViewHolder.read_counter)
if ("0" == message.msgtype) { // text message
} else if ("2" == message.msgtype) { // file transfer
messageViewHolder.msg_item.setText(message.filename.toString() + "\n" + message.filesize)
messageViewHolder.filename = message.filename
messageViewHolder.realname = message.msg
val file =
File(rootPath + message.filename)
if (file.exists()) {
} else {
}
} else { // image transfer
messageViewHolder.realname = message.msg
.apply(RequestOptions().override(1000, 1000))
.into(messageViewHolder.img_item)
}
val userModel: UserModel? = userList[message.uid]
messageViewHolder.msg_name.setText(userModel?.usernm)
if (userModel?.userphoto == null) {
.apply(requestOptions)
.into(messageViewHolder.user_photo)
} else {
.load(storageReference?.child("userPhoto/" + userModel.userphoto))
.apply(requestOptions)
.into(messageViewHolder.user_photo)
}
}
messageViewHolder.divider.visibility = View.INVISIBLE
if (message.timestamp == null) {
return
}
val day: String = dateFormatDay.format(message.timestamp)
val timestamp: String = dateFormatHour.format(message.timestamp)
messageViewHolder.timestamp.text = timestamp
if (position == 0) {
messageViewHolder.divider.visibility = View.VISIBLE
}
/*messageViewHolder.timestamp.setText("");
if (message.getTimestamp()==null) {return;}
String day = dateFormatDay.format( message.getTimestamp());
String timestamp = dateFormatHour.format( message.getTimestamp());
messageViewHolder.timestamp.setText(timestamp);
if (position==0) {
messageViewHolder.divider_date.setText(day);
messageViewHolder.divider.setVisibility(View.VISIBLE);
messageViewHolder.divider.getLayoutParams().height = 60;
};
beforeViewHolder.divider_date.setText(beforeDay);
beforeViewHolder.divider.setVisibility(View.VISIBLE);
beforeViewHolder.divider.getLayoutParams().height = 60;
}
beforeViewHolder = messageViewHolder;
beforeDay = day;*/ else {
val beforeMsg: Message = messageList!![position - 1]
val beforeDay: String = dateFormatDay.format(beforeMsg.timestamp)
if (day != beforeDay && beforeDay != null) {
messageViewHolder.divider.visibility = View.VISIBLE
}
}
}
private fun setReadCounter(message: Message, textView: TextView) {
if (cnt > 0) {
textView.visibility = View.VISIBLE
} else {
textView.visibility = View.INVISIBLE
}
}
override fun getItemCount() = messageList!!.size
init {
val dir = File(rootPath)
if (!helpers.isPermissionGranted(
activity!!,
permission.WRITE_EXTERNAL_STORAGE
)
) {
} else dir.mkdirs()
}
messageList = ArrayList<Message>()
setUnread2Read()
startListening()
}
}
inner class MessageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var user_photo: ImageView = view.findViewById(R.id.user_photo)
var msg_item: TextView = view.findViewById(R.id.msg_item)
var img_item: ImageView = view.findViewById(R.id.img_item) // only item_chatimage_
var msg_name: TextView = view.findViewById(R.id.msg_name)
var timestamp: TextView = view.findViewById(R.id.timestamp)
var read_counter: TextView = view.findViewById(R.id.read_counter)
var divider: LinearLayout = view.findViewById(R.id.divider)
var divider_date: TextView = view.findViewById(R.id.divider_date)
var button_item: TextView = view.findViewById(R.id.button_item) // only item_chatfile_
var msgLine_item: LinearLayout = view.findViewById(R.id.msgLine_item) // only item_chatfile_
var filename: String = ""
var realname: String = ""
var downloadClickListener = object : View.OnClickListener {
override fun onClick(view: View) {
download()
} else {
openWith()
}
}
fun download() {
if (!helpers.isPermissionGranted(activity!!, WRITE_EXTERNAL_STORAGE)
) {
return
}
showProgressDialog("Downloading File.")
val localFile = File(rootPath, filename)
storageReference?.child("files/" + realname)?.getFile(localFile)?.addOnSuccessListener{
button_item.setText("Open File")
hideProgressDialog()
Log.e("DirectTalk9 ", "local file created $localFile")
}?.addOnFailureListener{
Log.e("DirectTalk9 ", "local file not created $it")
}
}
@SuppressLint("ObsoleteSdkInt")
fun openWith() {
val newFile = File(rootPath + filename)
val mime = MimeTypeMap.getSingleton()
val type = mime.getMimeTypeFromExtension(ext)
val intent = Intent(Intent.ACTION_VIEW)
val uri: Uri
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context!!,activity!!.packageName + ".provider", newFile)
val resInfoList = activity!!.packageManager
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
activity!!.grantUriPermission(packageName,uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
} else {
uri = Uri.fromFile(newFile)
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, type)//"application/vnd.android.package-archive");
startActivity(Intent.createChooser(intent, "Your title"))
}
}
// photo view
private var imageClickListener = View.OnClickListener {
val intent = Intent(context, ViewPagerActivity::class.java)
intent.putExtra("roomID", roomID)
intent.putExtra("realname", realname)
startActivity(intent)
}
// file download and open
init {
// for file
msgLine_item.setOnClickListener(downloadClickListener)
img_item.setOnClickListener(imageClickListener)
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
코드가 너무 길어 변환한 코드 모두를 싣는다.
여기 필요한 모듈들이 좀 추가되어있는데 Message/NotificationModel/ViewPagerActivity이다. 이를 추가 해주다.
중간중간 코드들의 널여부를 몇개 바꾸었는데 ChatFragment 코드 모두를 아래와 같이 변환하였으니 참고하면된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
|
@Suppress("DEPRECATION")
class ChatFragment : Fragment() {
companion object {
fun getInstance(toUid: String?, roomID: String?): ChatFragment {
val thisfragment = ChatFragment()
val bdl = Bundle()
bdl.putString("toUid", toUid)
bdl.putString("roomID", roomID)
thisfragment.arguments = bdl
return thisfragment
}
}
val PICK_FROM_ALBUM = 1
val PICK_FROM_FILE = 2
var roomID: String? = null
var myUid: String? = null
var toUid: String? = null
val rootPath: String = helpers.rootPath + "/DirectTalk9/"
var recyclerView: RecyclerView? = null
lateinit var mAdapter: ChatRecyclerViewAdapter
@SuppressLint("SimpleDateFormat")
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")
@SuppressLint("SimpleDateFormat")
val dateFormatDay = SimpleDateFormat("yyyy-MM-dd")
@SuppressLint("SimpleDateFormat")
val dateFormatHour = SimpleDateFormat("aa hh:mm")
val userList = hashMapOf<String, UserModel>()
var listenerRegistration: ListenerRegistration? = null
var firestore: FirebaseFirestore? = null
var storageReference: StorageReference? = null
var linearLayoutManager: LinearLayoutManager? = null
var progressDialog: ProgressDialog? = null
var userCount = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_chat, container, false)
linearLayoutManager = LinearLayoutManager(context)
recyclerView?.layoutManager = linearLayoutManager
sendBtn.setOnClickListener {
sendMessage(msg, "0", null)
msg_input.setText("")
}
imageBtn.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = Media.CONTENT_TYPE
startActivityForResult(intent, PICK_FROM_ALBUM)
}
fileBtn.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI)
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(intent, "Select File"), PICK_FROM_FILE)
}
msg_input.setOnFocusChangeListener { _, hasFocus ->
if (!hasFocus)
helpers.hideKeyboard(activity!!)
}
if (arguments != null) {
roomID = arguments?.getString("roomID")
toUid = arguments?.getString("toUid")
}
firestore = FirebaseFirestore.getInstance()
storageReference = FirebaseStorage.getInstance().reference
dateFormatDay.timeZone = TimeZone.getTimeZone("Asia/Seoul")
dateFormatHour.timeZone = TimeZone.getTimeZone("Asia/Seoul")
myUid = FirebaseAuth.getInstance().currentUser?.uid
if ("" != toUid && toUid != null) { // find existing room for two user
findChatRoom(toUid!!)
} else if ("" != roomID && roomID != null) { // existing room (multi user)
setChatRoom(roomID!!)
}
if (roomID == null) { // new room for two user
getUserInfoFromServer(myUid)
getUserInfoFromServer(toUid)
userCount = 2
}
recyclerView?.addOnLayoutChangeListener { _, _, _, bottom, _, _, _, _, oldBottom ->
if (bottom < oldBottom) {
val lastAdapterItem = mAdapter.itemCount - 1
recyclerView?.post {
var recyclerViewPositionOffset = -1000000
val bottomView = linearLayoutManager?.findViewByPosition(lastAdapterItem)
linearLayoutManager?.scrollToPositionWithOffset(
lastAdapterItem,
recyclerViewPositionOffset
)
}
}
}
return view
}
private fun sendMessage(msg: String?, msgtype: String?, fileinfo: ChatModel.FileInfo?) {
sendBtn.isEnabled = false
if (roomID == null) { // create chatting room for two user
roomID = firestore?.collection("rooms")?.document()?.id
CreateChattingRoom(firestore!!.collection("rooms").document(roomID!!))
}
val messages = hashMapOf<String, Any?>()
messages["uid"] = myUid
messages["msg"] = msg
messages["msgtype"] = msgtype
messages["timestamp"] = FieldValue.serverTimestamp()
if (fileinfo != null) {
messages["filename"] = fileinfo.filename
messages["filesize"] = fileinfo.filesize
}
val docRef = firestore!!.collection("rooms").document(roomID!!)
if (!it.isSuccessful) {
return@addOnCompleteListener
}
val batch = firestore!!.batch()
// save last message
// save message
val readUsers: MutableList<String?> = mutableListOf()
readUsers.add(myUid)
messages["readUsers"] = readUsers //new String[]{myUid} );
batch.set(docRef.collection("messages").document(), messages)
// inc unread message count
val document = it.result
val users = document!!.get("users") as MutableMap<String, Long>?
for (key in users!!.keys) {
if (myUid != key) users[key] = users[key]!! + 1
}
document.reference.update("users", users)
if (it2.isSuccessful) {
//sendGCM();
sendBtn.isEnabled = true
}
}
}
}
fun CreateChattingRoom(room: DocumentReference) {
val users = hashMapOf<String, Int>()
val title = ""
val data = hashMapOf<String, Any?>()
data["title"] = null
data["users"] = users
if (it.isSuccessful) {
mAdapter = ChatRecyclerViewAdapter()
recyclerView!!.adapter = mAdapter
}
}
}
// Returns the room ID after locating the chatting room with the user ID.
private fun findChatRoom(toUid: String) {
firestore!!.collection("rooms").whereGreaterThanOrEqualTo("users.$myUid", 0).get()
.addOnCompleteListener {
if (!it.isSuccessful) return@addOnCompleteListener
if (users?.size == 2 && users[toUid]?.toInt() != null) {
setChatRoom(document.id)
break
}
}
}
}
// get user list in a chatting room
private fun setChatRoom(rid: String) {
roomID = rid
firestore?.collection("rooms")?.document(roomID!!)?.get()?.addOnCompleteListener {
if (!it.isSuccessful) {
return@addOnCompleteListener
}
val document = it.result
val users =
document!!.get("users") as Map<String, Long>?
for (key in users!!.keys) {
getUserInfoFromServer(key)
}
//document.getReference().update("users", users);
}
}
// get a user info
private fun getUserInfoFromServer(id: String?) {
firestore!!.collection("users").document(id!!).get().addOnSuccessListener {
val userModel = it.toObject(
UserModel::class.java
)
userList[userModel?.uid!!] = userModel
mAdapter = ChatRecyclerViewAdapter()
recyclerView!!.adapter = mAdapter
}
}
}
internal fun setUnread2Read() {
if (roomID == null) return
firestore!!.collection("rooms").document(roomID!!).get().addOnCompleteListener {
if (!it.isSuccessful) {
return@addOnCompleteListener
}
val document = it.result
val users = document!!.get("users") as MutableMap<String?, Long>
users[myUid] = 0.toLong()
document.reference.update("users", users)
}
}
fun getUserList(): Map<String, UserModel> = userList
internal fun sendGCM() {
val gson = Gson()
val notificationModel = NotificationModel()
notificationModel.notification.title = userList[myUid]?.usernm
notificationModel.data.title = userList[myUid]?.usernm
for ((_, value) in userList) {
val requestBody: RequestBody? = RequestBody.create(
MediaType.parse("application/json; charset=utf8"),
)
val request: Request? = Builder()
.header("Content-Type", "application/json")
.addHeader("Authorization", "key=")
.post(requestBody)
.build()
val okHttpClient = OkHttpClient()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {}
@Throws(IOException::class)
override fun onResponse(call: Call?, response: Response?) {
}
})
}
}
// uploading image / file
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK) return
val fileUri: Uri? = data!!.data
val filename: String = helpers.uniqueValue
showProgressDialog("Uploading selected File.")
val fileinfo: ChatModel.FileInfo? = getFileDetailFromUri(context!!, fileUri)
storageReference!!.child("files/$filename").putFile(fileUri!!)
.addOnCompleteListener {
sendMessage(filename, requestCode.toString(), fileinfo)
hideProgressDialog()
}
if (requestCode != PICK_FROM_ALBUM) {
return
}
// small image
.asBitmap()
.load(fileUri)
.apply(RequestOptions().override(150, 150))
.into(object : SimpleTarget<Bitmap?>() {
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap?>?
) {
val baos = ByteArrayOutputStream()
resource.compress(CompressFormat.JPEG, 100, baos)
val data: ByteArray? = baos.toByteArray()
storageReference!!.child("filesmall/$filename").putBytes(data!!)
}
})
}
fun showProgressDialog(title: String?) {
if (progressDialog == null) {
progressDialog = ProgressDialog(context)
}
progressDialog?.isIndeterminate = true
progressDialog?.setTitle(title)
progressDialog?.setMessage("Please wait..")
progressDialog?.setCancelable(false)
progressDialog?.show()
}
// get file name and size from Uri
fun getFileDetailFromUri(context: Context, uri: Uri?): ChatModel.FileInfo? {
if (uri == null) {
return null
}
val fileDetail: ChatModel.FileInfo = ChatModel.FileInfo()
// File Scheme.
val file = File(uri.path)
fileDetail.filename = file.name
fileDetail.filesize = helpers.size2String(file.length())
}
// Content Scheme.
val returnCursor: Cursor? =
if (returnCursor != null && returnCursor.moveToFirst()) {
val nameIndex =
returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val sizeIndex =
returnCursor.getColumnIndex(OpenableColumns.SIZE)
fileDetail.filename = returnCursor.getString(nameIndex)
fileDetail.filesize = helpers.size2String(returnCursor.getLong(sizeIndex))
}
}
return fileDetail
}
fun setProgressDialog(value: Int) {
progressDialog!!.progress = value
}
fun hideProgressDialog() = progressDialog!!.dismiss()
// =======================================================================================
inner class ChatRecyclerViewAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val requestOptions = RequestOptions().transforms(CenterCrop(), RoundedCorners(90))
internal var messageList: MutableList<Message>? = null
private var beforeDay: String? = null
internal var beforeViewHolder: MessageViewHolder? = null
fun startListening() {
beforeDay = null
messageList?.clear()
val roomRef: CollectionReference? =
firestore?.collection("rooms")?.document(roomID!!)?.collection("messages")
// my chatting room information
listenerRegistration = roomRef?.orderBy("timestamp")?.addSnapshotListener { p0, e ->
if (e != null) {
return@addSnapshotListener
}
var message: Message
for (change in p0!!.documentChanges) {
when (change.type) {
message = change.document.toObject<Message>(Message::class.java)
if (message.readUsers.indexOf(myUid) == -1) {
message.readUsers.add(myUid)
change.document.reference
.update("readUsers", message.getReadUsers())
}
messageList?.add(message)
notifyItemInserted(change.newIndex)
}
Type.MODIFIED -> {
message = change.document.toObject<Message>(
Message::class.java
)
messageList?.set(change.oldIndex, message)
notifyItemChanged(change.oldIndex)
}
Type.REMOVED -> {
messageList?.removeAt(change.oldIndex)
notifyItemRemoved(change.oldIndex)
}
}
}
recyclerView?.scrollToPosition(messageList!!.size - 1)
}
}
fun stopListening() {
if (listenerRegistration != null) {
listenerRegistration?.remove()
listenerRegistration = null
}
messageList?.clear()
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
val message: Message = messageList!![position]
when (message.msgtype) {
"1" -> R.layout.item_chatimage_right
"2" -> R.layout.item_chatfile_right
else -> R.layout.item_chatmsg_right
}
} else {
when (message.getMsgtype()) {
"1" -> R.layout.item_chatimage_left
"2" -> R.layout.item_chatfile_left
else -> R.layout.item_chatmsg_left
}
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
var view: View? = null
.inflate(viewType, parent, false)
return MessageViewHolder(view)
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val messageViewHolder: ChatFragment.MessageViewHolder =
holder as ChatFragment.MessageViewHolder
val message: Message = messageList!![position]
setReadCounter(message, messageViewHolder.read_counter)
if ("0" == message.msgtype) { // text message
} else if ("2" == message.msgtype) { // file transfer
messageViewHolder.msg_item.setText(message.filename.toString() + "\n" + message.filesize)
messageViewHolder.filename = message.filename
messageViewHolder.realname = message.msg
val file =
File(rootPath + message.filename)
if (file.exists()) {
} else {
}
} else { // image transfer
messageViewHolder.realname = message.msg
.apply(RequestOptions().override(1000, 1000))
.into(messageViewHolder.img_item)
}
val userModel: UserModel? = userList[message.uid]
messageViewHolder.msg_name.setText(userModel?.usernm)
if (userModel?.userphoto == null) {
.apply(requestOptions)
.into(messageViewHolder.user_photo)
} else {
.load(storageReference?.child("userPhoto/" + userModel.userphoto))
.apply(requestOptions)
.into(messageViewHolder.user_photo)
}
}
messageViewHolder.divider.visibility = View.INVISIBLE
if (message.timestamp == null) {
return
}
val day: String = dateFormatDay.format(message.timestamp)
val timestamp: String = dateFormatHour.format(message.timestamp)
messageViewHolder.timestamp.text = timestamp
if (position == 0) {
messageViewHolder.divider.visibility = View.VISIBLE
}
/*messageViewHolder.timestamp.setText("");
if (message.getTimestamp()==null) {return;}
String day = dateFormatDay.format( message.getTimestamp());
String timestamp = dateFormatHour.format( message.getTimestamp());
messageViewHolder.timestamp.setText(timestamp);
if (position==0) {
messageViewHolder.divider_date.setText(day);
messageViewHolder.divider.setVisibility(View.VISIBLE);
messageViewHolder.divider.getLayoutParams().height = 60;
};
beforeViewHolder.divider_date.setText(beforeDay);
beforeViewHolder.divider.setVisibility(View.VISIBLE);
beforeViewHolder.divider.getLayoutParams().height = 60;
}
beforeViewHolder = messageViewHolder;
beforeDay = day;*/ else {
val beforeMsg: Message = messageList!![position - 1]
val beforeDay: String = dateFormatDay.format(beforeMsg.timestamp)
if (day != beforeDay && beforeDay != null) {
messageViewHolder.divider.visibility = View.VISIBLE
}
}
}
private fun setReadCounter(message: Message, textView: TextView) {
if (cnt > 0) {
textView.visibility = View.VISIBLE
} else {
textView.visibility = View.INVISIBLE
}
}
override fun getItemCount() = messageList!!.size
init {
val dir = File(rootPath)
if (!helpers.isPermissionGranted(
activity!!,
permission.WRITE_EXTERNAL_STORAGE
)
) {
} else dir.mkdirs()
}
messageList = ArrayList<Message>()
setUnread2Read()
startListening()
}
}
inner class MessageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var user_photo: ImageView = view.findViewById(R.id.user_photo)
var msg_item: TextView = view.findViewById(R.id.msg_item)
var img_item: ImageView = view.findViewById(R.id.img_item) // only item_chatimage_
var msg_name: TextView = view.findViewById(R.id.msg_name)
var timestamp: TextView = view.findViewById(R.id.timestamp)
var read_counter: TextView = view.findViewById(R.id.read_counter)
var divider: LinearLayout = view.findViewById(R.id.divider)
var divider_date: TextView = view.findViewById(R.id.divider_date)
var button_item: TextView = view.findViewById(R.id.button_item) // only item_chatfile_
var msgLine_item: LinearLayout = view.findViewById(R.id.msgLine_item) // only item_chatfile_
var filename: String = ""
var realname: String = ""
var downloadClickListener = object : View.OnClickListener {
override fun onClick(view: View) {
download()
} else {
openWith()
}
}
fun download() {
if (!helpers.isPermissionGranted(activity!!, WRITE_EXTERNAL_STORAGE)
) {
return
}
showProgressDialog("Downloading File.")
val localFile = File(rootPath, filename)
storageReference?.child("files/" + realname)?.getFile(localFile)?.addOnSuccessListener{
button_item.setText("Open File")
hideProgressDialog()
Log.e("DirectTalk9 ", "local file created $localFile")
}?.addOnFailureListener{
Log.e("DirectTalk9 ", "local file not created $it")
}
}
@SuppressLint("ObsoleteSdkInt")
fun openWith() {
val newFile = File(rootPath + filename)
val mime = MimeTypeMap.getSingleton()
val type = mime.getMimeTypeFromExtension(ext)
val intent = Intent(Intent.ACTION_VIEW)
val uri: Uri
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context!!,activity!!.packageName + ".provider", newFile)
val resInfoList = activity!!.packageManager
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
activity!!.grantUriPermission(packageName,uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
} else {
uri = Uri.fromFile(newFile)
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, type)//"application/vnd.android.package-archive");
startActivity(Intent.createChooser(intent, "Your title"))
}
}
// photo view
private var imageClickListener = View.OnClickListener {
val intent = Intent(context, ViewPagerActivity::class.java)
intent.putExtra("roomID", roomID)
intent.putExtra("realname", realname)
startActivity(intent)
}
// file download and open
init {
// for file
msgLine_item.setOnClickListener(downloadClickListener)
img_item.setOnClickListener(imageClickListener)
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |