오늘보다 더 나은 내일의 나에게_

비전공자의 IoT 국비 교육 수강일지 Day_90 본문

비전공자의 코딩일지

비전공자의 IoT 국비 교육 수강일지 Day_90

chan_96 2022. 4. 26. 12:28
728x90

안드로이드

실습

📌코드

ChatAdapter 코드
package com.example.ex0425;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class ChatAdapter extends BaseAdapter {
    
    Context context;
    int layout;
    ArrayList<ChatVO> list;
    LayoutInflater inflater; // xml -> view로 변환해주는 역할
    String currentId; // 현재 로그인 아이디

    public ChatAdapter(Context context, int layout, ArrayList<ChatVO> list, String currentId) {
        this.context = context;
        this.layout = layout;
        this.list = list;
        this.currentId = currentId;
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {

        if(view==null){
            //view는 chat_item.xml의 정보를 가진 객체
            view = inflater.inflate(layout,viewGroup,false);
        }

        // 상대방과 자신의 내용을 보여줄 View 초기화
        ImageView imgOther = view.findViewById(R.id.imgOther);
        TextView tvOtherNm = view.findViewById(R.id.tvOtherNm);
        TextView tvOtherMsg = view.findViewById(R.id.tvOtherMsg);
        TextView tvOtherTime = view.findViewById(R.id.tvOtherTime);
        TextView tvMyMsg = view.findViewById(R.id.tvMyMsg);
        TextView tvMyTime = view.findViewById(R.id.tvMyTime);

        ChatVO vo = list.get(position);

        //현재 로그인한 아이디 판단 -> View 가시성 설정
        //상대방 아이디인 경우: 왼쪽 View만 보여지도록 설정(imgOther, tvOtherNm, tvOtherMsg, tvOtherTime)
        //자신의 아이디인 경우: 오른쪽 View만 보여지도록 설정(tvMyMsg, tvMyTime)

        if (list.get(position).getName().equals(currentId)) {
            imgOther.setVisibility(View.INVISIBLE);
            tvOtherNm.setVisibility(View.INVISIBLE);
            tvOtherMsg.setVisibility(View.INVISIBLE);
            tvOtherTime.setVisibility(View.INVISIBLE);

            tvMyMsg.setText(vo.getMsg());
            tvMyTime.setText(vo.getTime());
        }else{
            imgOther.setImageResource(vo.getImgId());
            tvOtherNm.setText(vo.getName());
            tvOtherMsg.setText(vo.getMsg());
            tvOtherTime.setText(vo.getTime());
        }

        return view;
    }
}

ChatActivity 코드
package com.example.ex0425;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class ChatActivity extends AppCompatActivity {

    ListView chatList;
    ChatAdapter adapter;
    ArrayList<ChatVO> list;

    EditText edtMsg;
    Button btnSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        chatList = findViewById(R.id.rcChatlist);
        edtMsg = findViewById(R.id.edtMsg);
        btnSend = findViewById(R.id.btnSend);
        list = new ArrayList<>();

        String currentId = getIntent().getStringExtra("login_id");
        Log.d("ChatActivity","현재 로그인한 아이디: "+currentId);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("talk");

        //1.버튼 클릭 시 입력된 메시지를 파이어베이스 데이터베이스에 저장
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //현재 시간 구하기(스마트폰시간)
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                String time = sdf.format(cal.getTime());

                String msg = edtMsg.getText().toString();

                myRef.push().setValue(new ChatVO
                            (R.drawable.ic_launcher_background,
                                    currentId,
                                    msg,
                                    time
                            ));
            }
        });

        //2.파이어베이스 데이터베이스에 저장된 데이터를 가져온 후 list객체에 저장
        myRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                ChatVO vo = snapshot.getValue(ChatVO.class);
                list.add(vo);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        adapter = new ChatAdapter(ChatActivity.this,
                                    R.layout.chat_item,
                                    list,
                                    currentId);

        chatList.setAdapter(adapter);
    }
}


LoginActivity 코드

package com.example.ex0425;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {

    EditText edtUserId, edtUserPw;
    Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        edtUserId = findViewById(R.id.edtUserId);
        edtUserPw = findViewById(R.id.edtUserPw);
        btnLogin = findViewById(R.id.btnLogin);

        //버튼 클릭 시 ChatActivity로 화면전환
        //로그인한 id를 전달하기

        String[] userIdList = {"smhrd","hc"};
        String[] userPwList = {"1234","1234"};

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String id = edtUserId.getText().toString();
                String pw = edtUserPw.getText().toString();

                for(int i=0;i<userIdList.length;i++){

                    if(id.equals(userIdList[i]) && pw.equals(userPwList[i])){
                        Intent intent = new Intent(LoginActivity.this,ChatActivity.class);

                        intent.putExtra("login_id",id);

                        startActivity(intent);

                        break;
                    }
                    
                    if(i==userIdList.length-1){
                        Toast.makeText(LoginActivity.this,
                                "다시 로그인 해주세요.",
                                Toast.LENGTH_SHORT).show();
                    }

                }//end for
            }//end onClick
        });//end SetOnClickListener


    }
}​
728x90
Comments