Android- 로그인 및 채팅기능2(Firebase)
- 로그인을하면 채팅을 할수있다 (카톡과비슷하게 디자인해보았다.) 그리고 오른쪽 위 내프로필 버튼을 누르면 나의 정보를 확일할수있다.
메인 로그인 페이지
MainActivity
public class MainActivity extends AppCompatActivity {
EditText email,pass;
FirebaseAuth firebaseAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
firebaseAuth= FirebaseAuth.getInstance();
getSupportActionBar().setTitle("로그인");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_acount);
email=findViewById(R.id.email);
pass = findViewById(R.id.pass);
Button login = findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String strEmail=email.getText().toString();
String strPass = pass.getText().toString();
firebaseAuth.signInWithEmailAndPassword(strEmail, strPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
System.out.println("로그인성공!");
Intent intent =new Intent(MainActivity.this, ChatActivity.class);
startActivity(intent);
}else{
System.out.print("로그인실패!");
}
}
});
}
});
//회원가입
Button register=findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String strEmail =email.getText().toString();
String strPass=pass.getText().toString();
firebaseAuth.createUserWithEmailAndPassword(strEmail, strPass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
System.out.println("회원가입성공!");
}else{
System.out.print("회원가입실패!");
}
}
});
}
});
}
public void checkPermission(){
String[] permissions= { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA };
ArrayList<String> noPermissions=new ArrayList<>();
for(String permission:permissions){
if(ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
noPermissions.add(permission);
}
}
if(noPermissions.size() > 0){
String[] reqPermissions=noPermissions.toArray(new String[noPermissions.size()]);
ActivityCompat.requestPermissions(this, reqPermissions,100);
}
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:layout_marginTop="200sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30sp">
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="이메일"
android:text="test01@test.com"/>
<EditText
android:id="@+id/pass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="패스워드"
android:text="12341234"/>
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="로그인"/>
<Button
android:id="@+id/register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="회원가입"/>
</LinearLayout>
</RelativeLayout>
-> 앞의 게시글들과 똑같은 로그인하는 페이지이다.
나의페이지
MypageActivity
public class MypageActivity extends AppCompatActivity {
FirebaseUser user;
CircleImageView image;
String strFile;
EditText name,address;
FirebaseDatabase db;
DatabaseReference ref;
UserVO userVO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mypage);
user = FirebaseAuth.getInstance().getCurrentUser();
getSupportActionBar().setTitle("My Page | " + user.getEmail());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
name=findViewById(R.id.name);
address=findViewById(R.id.address);
db=FirebaseDatabase.getInstance();
//저장된 정보출력
ref =db.getReference("users").child(user.getUid());
ref.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
userVO=task.getResult().getValue(UserVO.class);
if(userVO !=null){ //데이터가있으면
System.out.println(userVO.toString());
name.setText(userVO.getName());
address.setText(userVO.getAddress());
if(!userVO.getImage().equals("") || userVO.getImage() !=null){
Picasso.with(MypageActivity.this)
.load(userVO.getImage())
.into(image);
}
}
}
});
//이미지를 클릭했을때
image=findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});
//저장버튼을 클릭한 경우
TextView save = findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder box = new AlertDialog.Builder(MypageActivity.this);
box.setTitle("질의");
box.setMessage("변경된 정보를 저장하실래요?");
box.setPositiveButton("예", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//이미지 업로드
Uri uriFile= Uri.fromFile(new File(strFile));
String strImage=strFile.substring(strFile.lastIndexOf("/")+1);
StorageReference storage = FirebaseStorage.getInstance().getReference();
storage.child("image/"+strImage).putFile(uriFile)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> result =taskSnapshot.getStorage().getDownloadUrl();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
System.out.println("......."+uri.toString());
//정보저장
UserVO vo = new UserVO();
vo.setImage(uri.toString());
vo.setName(name.getText().toString());
vo.setAddress(address.getText().toString());
vo.setKey(user.getUid());
System.out.println(vo.toString());
ref=db.getReference("/users").child(user.getUid());
ref.push();
vo.setKey(ref.getKey());
ref.setValue(vo);
}
});
}
});
}
});
box.setNegativeButton("아니오",null);
box.show();
}
});
}
//앨범에서 사진을 선택 후
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode==0){
image.setImageURI(data.getData());
Cursor cursor =getContentResolver().query(data.getData(), null,null,null,null);
cursor.moveToFirst();
strFile= cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
System.out.println("......"+strFile);
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
activity_mypage
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MypageActivity"
android:gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="30sp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/image"
android:layout_width="200sp"
android:layout_height="200sp"
android:src="@drawable/ic_person"
app:civ_border_width="2sp"
app:civ_border_color="#000000"
android:layout_gravity="center"
android:layout_marginBottom="40sp"
android:layout_marginTop="40sp"/>
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="이름"
android:fontFamily="@font/kang"
android:layout_marginBottom="20sp"/>
<EditText
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="주소"
android:fontFamily="@font/kang"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:padding="30sp"
android:layout_margin="10sp">
<TextView
android:id="@+id/save"
android:layout_width="0sp"
android:layout_height="30sp"
android:layout_weight="1"
android:text="저장"
android:gravity="center"
android:background="@drawable/border"
android:layout_marginRight="10sp"
android:textColor="#FFFFFF"
android:fontFamily="@font/kang"/>
<TextView
android:id="@+id/cancel"
android:layout_width="0sp"
android:layout_height="30sp"
android:layout_weight="1"
android:text="취소"
android:gravity="center"
android:background="@drawable/border"
android:layout_marginLeft="10sp"
android:textColor="#FFFFFF"
android:fontFamily="@font/kang"/>
</LinearLayout>
</RelativeLayout>
-> 사진은 카메라 파일안에서 가져올수있고 이름과 주소를 입력해서 저장이 가능하다. 저장을하고나면 마이페이지를 클릭했을때 나의 정보를 볼수가있다.
채팅
ChatActivity
public class ChatActivity extends AppCompatActivity {
FirebaseUser user;
EditText contents;
FirebaseDatabase db;
DatabaseReference refChat;
ArrayList<ChatVO> array=new ArrayList<>();
ChatAdapter chatAdapter= new ChatAdapter();
RecyclerView list;
public void CallList(){
refChat=db.getReference("chats");
refChat.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
ChatVO vo = snapshot.getValue(ChatVO.class);
array.add(vo);
System.out.println(vo.toString());
chatAdapter.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) {
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
db=FirebaseDatabase.getInstance();
user= FirebaseAuth.getInstance().getCurrentUser();
getSupportActionBar().setTitle("채팅 | "+ user.getEmail());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contents=findViewById(R.id.contents);
ImageView send = findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String strContents=contents.getText().toString();
if(strContents.equals("")){
Toast.makeText(ChatActivity.this,"내용을 입력하세요!", Toast.LENGTH_SHORT).show();
}else{
ChatVO vo =new ChatVO();
vo.setContents(strContents);
vo.setUid(user.getUid());
vo.setEmail(user.getEmail());
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
vo.setDate(sdf.format(new Date()));
refChat=db.getReference("chats").push();
vo.setKey(refChat.getKey());
refChat.setValue(vo);
contents.setText("");
}
}
});
CallList();
RecyclerView list=findViewById(R.id.list);
list.setAdapter(chatAdapter);
list.setLayoutManager(new LinearLayoutManager(this));
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
finish();
break;
case R.id.mypage:
Intent intent = new Intent(this, MypageActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chat, menu);
return super.onCreateOptionsMenu(menu);
}
//채팅어댑터
class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder>{
@NonNull
@Override
public ChatAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view =getLayoutInflater().inflate(R.layout.item_chat,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ChatVO vo =array.get(position);
RelativeLayout.LayoutParams pcontent=
(RelativeLayout.LayoutParams)holder.contents.getLayoutParams();
RelativeLayout.LayoutParams pdate=
(RelativeLayout.LayoutParams)holder.date.getLayoutParams();
RelativeLayout.LayoutParams pemail=
(RelativeLayout.LayoutParams)holder.email.getLayoutParams();
RelativeLayout.LayoutParams pimage=
(RelativeLayout.LayoutParams)holder.image.getLayoutParams();
if(vo.getEmail().equals(user.getEmail())){ //내가쓴메시지
holder.image.setVisibility(View.GONE);
holder.email.setVisibility(View.GONE);
pcontent.leftMargin=800;
pdate.leftMargin=700;
}else{ //다른사람 메시지
holder.image.setVisibility(View.VISIBLE);
holder.email.setVisibility(View.VISIBLE);
holder.contents.setBackgroundResource(R.drawable.left_bubble);
}
holder.contents.setText(vo.getContents());
holder.email.setText(vo.getEmail());
holder.date.setText(vo.getDate());
//이미지 불러오기
DatabaseReference refUser=db.getReference("users");
refUser.child(vo.getUid()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
UserVO uvo=task.getResult().getValue(UserVO.class);
if(uvo != null){
if(!uvo.getImage().equals("") || uvo.getImage()!=null){
Picasso.with(ChatActivity.this)
.load(uvo.getImage())
.into(holder.image);
}
}else{
holder.image.setImageResource(R.drawable.ic_person);
}
}
});
}
@Override
public int getItemCount() {
return array.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView contents,email,date;
public ViewHolder(@NonNull View itemView) {
super(itemView);
image=itemView.findViewById(R.id.image);
contents=itemView.findViewById(R.id.contents);
email=itemView.findViewById(R.id.email);
date=itemView.findViewById(R.id.date);
}
}
}
}
item_chat
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="10sp"
android:background="#9bbbd4"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/image"
android:layout_width="50sp"
android:layout_height="80sp"
android:src="@drawable/ic_person"
app:civ_border_color="#000000"
app:civ_border_width="2sp" />
<TextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test01@test.com"
android:fontFamily="@font/kang"
android:layout_marginLeft="10sp"
android:layout_toRightOf="@id/image"/>
<TextView
android:id="@+id/contents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="안녕하세요!"
android:fontFamily="@font/kang"
android:layout_toRightOf="@id/image"
android:layout_marginLeft="20sp"
android:layout_marginTop="10sp"
android:padding="15sp"
android:layout_below="@id/email"
android:background="@drawable/bubble"/>
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/contents"
android:layout_marginLeft="30sp"
android:layout_marginTop="10sp"
android:layout_toRightOf="@id/image"
android:fontFamily="@font/kang"
android:text="2022-03-03 14:22:30"
android:textSize="10sp" />
</RelativeLayout>
LinearLayout 으로 원래 디자인을했었는데 LayoutParams을 줄때 gravity 속성을 줄수없었다 ㅠㅠ .. RelativeLayout 디자인이 훨깔끔하고 보기가좋아서 써보겠다고 나름이것저것찾아서 그냥 margin 으로 내가보낸메세지는 오른쪽에 위치하도록하였다. 더좋은방법이 있을거같지만 현재로선 잘모르겠다. 뭔가 찝찝한느낌.. 여튼 기록해두고 다음에 방법을 찾게되면 고쳐보자
activity_chat
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="0sp"
android:layout_weight="1" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10sp">
<EditText
android:id="@+id/contents"
android:layout_width="300sp"
android:layout_height="40sp"
android:layout_marginLeft="50sp"
android:background="@drawable/border2" />
<ImageView
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_send"
android:layout_alignParentRight="true"
android:layout_margin="10sp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_baseline_add_24"
android:layout_alignParentLeft="true"
android:layout_margin="10sp" />
</RelativeLayout>
</LinearLayout>
최종완성!
어설프게따라해봤다. 끄읕
댓글남기기