Skip to content

Commit

Permalink
[feat] #111 Chatting Connection
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-j0y committed Mar 24, 2022
1 parent 52af15d commit 1bfbad3
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 97 deletions.
4 changes: 2 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@

<application
android:name=".util.InfraApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.InfraAndroid"
android:usesCleartextTraffic="true"
android:requestLegacyExternalStorage="true">
android:requestLegacyExternalStorage="true"
android:dataExtractionRules="@xml/data_extraction_rules">
<activity
android:name=".MainActivity"
android:exported="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import retrofit2.Response

class CategoryViewIdeaFragment : BaseFragment<FragmentViewIdeaBinding>(R.layout.fragment_view_idea){
private var writerId : String ?= null
private var opponentProfileImg : String ?= null

override fun FragmentViewIdeaBinding.onCreateView(){

Expand All @@ -52,7 +53,9 @@ class CategoryViewIdeaFragment : BaseFragment<FragmentViewIdeaBinding>(R.layout.
if(response.isSuccessful){
when(response.body()?.code){
1000 -> { binding.viewIdea = response.body()?.result
writerId = response.body()?.result?.user_nickname }
writerId = response.body()?.result?.user_nickname
opponentProfileImg = response.body()?.result?.user_prPhoto
}
}
}
}
Expand All @@ -63,7 +66,7 @@ class CategoryViewIdeaFragment : BaseFragment<FragmentViewIdeaBinding>(R.layout.
})

binding.startChattingImageButton.setOnClickListener {
val action = CategoryViewIdeaFragmentDirections.actionCategoryViewIdeaFragmentToChatFragment(writerId = writerId)
val action = CategoryViewIdeaFragmentDirections.actionCategoryViewIdeaFragmentToChatFragment(writerId = writerId, opponentProfileImg)
it.findNavController().navigate(action)
}

Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ data class MessageInfo(
var senderId: String = "",
var message: String = "",
var sendTime : String = "",
var profileImg : String? = "",
var dateLine : Boolean = true,
)
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,14 @@ import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import androidx.room.Room
import com.example.infraandroid.util.InfraApplication
import com.example.infraandroid.R
import com.example.infraandroid.chat.model.ChatRoomDB
import com.example.infraandroid.chat.model.ChatRoomEntity
import com.example.infraandroid.chat.model.MessageInfo
import com.example.infraandroid.databinding.FragmentChatBinding
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.*
import com.google.firebase.database.ktx.database
import com.google.firebase.database.ktx.getValue
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap
Expand All @@ -36,8 +28,9 @@ class ChatFragment : Fragment() {
private val chatAdapter = ChatMultiViewAdapter()
private val database = Firebase.database
val chatList = mutableListOf<MessageInfo>()
private var chatRoomDB : ChatRoomDB? = null

private var chatRoomIndex : Int? = null
private val mRef = database.getReference("chatting")
private val args: ChatFragmentArgs by navArgs()

override fun onCreateView(
inflater: LayoutInflater,
Expand All @@ -47,17 +40,20 @@ class ChatFragment : Fragment() {

val binding = FragmentChatBinding.inflate(inflater, container, false)
mBinding = binding

return mBinding?.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

val args: ChatFragmentArgs by navArgs()
val opponentNickName = args.writerId
val opponentProfileImg = args.opponenetProfileImg

val buttonToSend = mBinding?.messageSendButton as ImageButton
mBinding?.chatOpponentNameTextview?.text = opponentNickName


// 리사이클러뷰
mBinding?.chatRecyclerview?.adapter = chatAdapter

Expand All @@ -66,11 +62,10 @@ class ChatFragment : Fragment() {
var date = ""
override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {

// A new comment has been added, add it to the displayed list
chatList.clear()
val tempMessage = MessageInfo("","","")
val tempMessage = MessageInfo("","","", opponentProfileImg)
for(snapshot in dataSnapshot.children){
Log.d(TAG, "onChildAdded: "+ snapshot.key.toString())
Log.d(TAG, "onChildAdded: ${snapshot.value.toString()}")
if(snapshot.key=="senderId"){
tempMessage.senderId=snapshot.value.toString()
}
Expand All @@ -87,12 +82,12 @@ class ChatFragment : Fragment() {
date = thisMessageTime
}
}
// if(snapshot.key=="user1") {
// opponentId = snapshot.value.toString()
// }
}
if(tempMessage.senderId!="" && tempMessage.message!="" && tempMessage.sendTime!="")
{
Log.d(TAG, "onChildAdded: $tempMessage")
chatList.add(tempMessage)
}
chatAdapter.messageList.addAll(chatList)
chatAdapter.notifyDataSetChanged()
// ...
Expand Down Expand Up @@ -138,24 +133,39 @@ class ChatFragment : Fragment() {
}
}

var chatRoomIndex : Int ?= null
chatRoomDB = ChatRoomDB.getInstance(context!!.applicationContext)
CoroutineScope(Dispatchers.IO).launch{
if (opponentNickName != null) {
if (chatRoomDB!!.chatRoomDAO().checkOpponent(opponentNickName).isEmpty()){
var newChatRoomEntity : ChatRoomEntity ?= null
newChatRoomEntity?.opponentNickName = opponentNickName
if (newChatRoomEntity != null) {
chatRoomDB!!.chatRoomDAO().insert(newChatRoomEntity)

mRef.addValueEventListener(object:ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
// 이미 파이어베이스에 존재하는 채팅방인지 검사
if(chatRoomIndex==null){
var i = 0
for(chatIndex in snapshot.children){
i += 1
if(chatIndex.child("users").child("user1").value.toString()==opponentNickName &&
chatIndex.child("users").child("user2").value.toString()==InfraApplication.prefs.getString("userNickName", "null")){
chatRoomIndex = i
break
}
if(chatIndex.child("users").child("user2").value.toString()==opponentNickName &&
chatIndex.child("users").child("user1").value.toString()==InfraApplication.prefs.getString("userNickName", "null")){
chatRoomIndex = i
break
}
}
// 처음 시작하는 채팅이면
if(chatRoomIndex==null){
chatRoomIndex = snapshot.childrenCount.toInt()+1
}
chatRoomIndex = chatRoomDB!!.chatRoomDAO().checkOpponent(opponentNickName)[0].index
mRef.child(chatRoomIndex.toString()).addChildEventListener(childEventListener)
Log.d(TAG, "onDataChange: $chatRoomIndex")
}
}
}

override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}

val databaseReference = database.getReference("chatting").child(chatRoomIndex.toString())
databaseReference.addChildEventListener(childEventListener)
})

// 보내기 버튼을 누르면 firebase realtime db에 저장
buttonToSend.setOnClickListener {
Expand All @@ -164,17 +174,18 @@ class ChatFragment : Fragment() {
val date = Date(now)
val dataFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val dateTime = dataFormat.format(date)
val myRef = database.getReference("chatting").child(chatRoomIndex.toString()).child(dateTime)
Log.d(TAG, "왜 여기는 되냐 "+mRef.child(chatRoomIndex.toString()))
val myRef = mRef.child(chatRoomIndex.toString()).child(dateTime)

// 대화하는 두 사람의 Id값을 firebase realtime db에 저장
val userRef = database.getReference("chatting").child(chatRoomIndex.toString()).child("users")
val lastMessageRef = database.getReference("chatting").child(chatRoomIndex.toString()).child("lastMessage")
val userRef = mRef.child(chatRoomIndex.toString()).child("users")
val lastMessageRef = mRef.child(chatRoomIndex.toString()).child("lastMessage")
val userHashMap = HashMap<String, String>()
userHashMap["user1"] = InfraApplication.prefs.getString("userNickName", "null")
// 상대방의 아이디 가져와서 user2에 저장
userHashMap["user2"] = opponentNickName.toString()
userHashMap["user1ProfileImg"] = "user1의 프로필 이미지 url"
userHashMap["user2ProfileImg"] = "user2의 프로필 이미지 url"
userHashMap["user2ProfileImg"] = opponentProfileImg.toString()
userRef.setValue(userHashMap)

if (messageToSend != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ class ChatMultiViewAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>(){
}

Glide.with(itemView)
.load(R.drawable.other_user_photo)
.load(messageInfo.profileImg)
.circleCrop()
.error(R.drawable.other_user_photo)
.into(binding.opponentProfileImageview)

var hour = messageInfo.sendTime.substring(11..12)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ class ChattingRoomAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
binding.chattingRoomLastMessageTextview.text = chattingRoomInfo.lastMessage
binding.chattingRoomListOpponentNameTextview.text = chattingRoomInfo.opponentName
Glide.with(itemView)
.load(R.drawable.other_user_photo)
.load(chattingRoomInfo.opponentProfileImg)
.circleCrop()
.error(R.drawable.other_user_photo)
.into(binding.chattingRoomListImageview)
itemView.setOnClickListener {
InfraApplication.chatRoomIndex = chattingRoomInfo.chattingRoomIndex
it.findNavController().navigate(R.id.action_chatting_room_list_fragment_to_chat_fragment)
val action = ChattingRoomListFragmentDirections.actionChattingRoomListFragmentToChatFragment(chattingRoomInfo.opponentName, chattingRoomInfo.opponentProfileImg)
it.findNavController().navigate(action)
}

val now: Long = System.currentTimeMillis()
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/res/navigation/nav_graph.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
app:argType="string"
app:nullable="true"
android:defaultValue="@null"/>
<argument
android:name="opponenetProfileImg"
app:argType="string"
app:nullable="true"
android:defaultValue="@null"/>
</fragment>
<fragment
android:id="@+id/my_info_fragment"
Expand Down
36 changes: 36 additions & 0 deletions app/src/main/res/xml/data_extraction_rules.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!--
TODO: Use <include> and <exclude> to control what is backed up.
The domain can be file, database, sharedpref, external or root.
Examples:
<include domain="file" path="file_to_include"/>
<exclude domain="file" path="file_to_exclude"/>
<include domain="file" path="include_folder"/>
<exclude domain="file" path="include_folder/file_to_exclude"/>
<exclude domain="file" path="exclude_folder"/>
<include domain="file" path="exclude_folder/file_to_include"/>
<include domain="sharedpref" path="include_shared_pref1.xml"/>
<include domain="database" path="db_name/file_to_include"/>
<exclude domain="database" path="db_name/include_folder/file_to_exclude"/>
<include domain="external" path="file_to_include"/>
<exclude domain="external" path="file_to_exclude"/>
<include domain="root" path="file_to_include"/>
<exclude domain="root" path="file_to_exclude"/>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>

0 comments on commit 1bfbad3

Please sign in to comment.