• 로그인을 하면 메모장목록이나오고 메모장글을 등록가능하고 오른쪽 위 채팅을 누르면 다른 사용자간의 대화를 할수있다. 내가보낸것은 오른쪽 상대가 보낸메세지는 왼쪽에 출력된다.

Main 로그인부분

MainActivity.java

public class MainActivity extends AppCompatActivity {
    EditText email, pass;
    FirebaseAuth firebaseAuth;

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

        firebaseAuth=FirebaseAuth.getInstance();

        getSupportActionBar().setTitle("로그인");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_person);

        email=findViewById(R.id.email);
        pass=findViewById(R.id.pass);

        Button btn= findViewById(R.id.login);
        //로그인버튼을 클릭한경우
        btn.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(MainActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(MainActivity.this, "로그인 성공!", Toast.LENGTH_SHORT).show();
                                    System.out.println("..........로그인성공");
                                    Intent intent = new Intent(MainActivity.this, MemoActivity.class);
                                    startActivity(intent);
                                }else{
                                    Toast.makeText(MainActivity.this, "로그인 실패!", Toast.LENGTH_SHORT).show();
                                    System.out.println("..........로그인실패");
                                }
                            }
                        });
            }
        });

        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(MainActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if(task.isSuccessful()){
                                    System.out.println("등록성공");
                                }else{
                                    System.out.println("등록실패");

                                }
                            }
                        });

            }
        });
    }
}

activity_main

<?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=".MainActivity"
    android:padding="30sp"
    android:orientation="vertical"
    android:layout_marginTop="200sp">

    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="이메일"
        android:fontFamily="@font/ho"
        android:text="test01@test.com"/>

    <EditText
        android:id="@+id/pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="비밀번호"
        android:fontFamily="@font/ho"
        android:text="12341234"/>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="로그인"
        android:fontFamily="@font/kang"
        />

    <Button
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="회원가입"
        android:fontFamily="@font/kang"
        />

</LinearLayout>

메인로그인

메모장

MemoActivity

public class MemoActivity extends AppCompatActivity {
    FirebaseUser user;
    FirebaseDatabase db;
    DatabaseReference ref;
    ArrayList<MemoVO> array=new ArrayList<>();
    MemoAdapter memoAdapter=new MemoAdapter();
   
    @Override
    protected void onRestart() {
        array.clear();
        callList();
        super.onRestart();
    }

    //메모목록 데이터
    public void callList(){
        db=FirebaseDatabase.getInstance();
        ref=db.getReference("memos").child(user.getUid());
        ref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                MemoVO vo=(MemoVO)snapshot.getValue(MemoVO.class);
                array.add(vo);
                System.out.println(vo.toString());
                memoAdapter.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_memo);

        user= FirebaseAuth.getInstance().getCurrentUser();
        getSupportActionBar().setTitle("메모장 | " + user.getEmail());
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        callList();
        FloatingActionButton edit=findViewById(R.id.edit);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MemoActivity.this, InsertActivity.class);
                startActivity(intent);
            }
        });

        RecyclerView list=findViewById(R.id.list);
        list.setAdapter(memoAdapter);
        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.chat:
                Intent intent = new Intent(this,ChatActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //메모 어댑터
    class MemoAdapter extends RecyclerView.Adapter<MemoAdapter.ViewHolder>{
        @NonNull
        @Override
        public MemoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view=getLayoutInflater().inflate(R.layout.item_memo,parent,false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MemoAdapter.ViewHolder holder, int position) {
            MemoVO vo=array.get(position);
            holder.contents.setText(vo.getContents());
            holder.date.setText(vo.getDate());
            holder.item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent=new Intent(MemoActivity.this, ReadActivity.class);
                    intent.putExtra("vo", (Serializable) vo);
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            CardView item;
            TextView date, contents;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                item=itemView.findViewById(R.id.item);
                date=itemView.findViewById(R.id.date);
                contents=itemView.findViewById(R.id.contents);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.memo, menu);
        return super.onCreateOptionsMenu(menu);
    }
}//Activity

activity_memo

<?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=".MemoActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_edit"
        android:id="@+id/edit"
        android:backgroundTint="#E2D0F9"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_margin="10sp"
        app:borderWidth="0sp"/>
</RelativeLayout>

item_memo

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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:layout_margin="5sp"
    android:padding="20sp"
    app:cardCornerRadius="10sp"
    android:id="@+id/item">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_marginTop="20sp">

        <TextView
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="메모작성날짜"
            android:textColor="#317773"
            android:fontFamily="@font/kang"/>

        <TextView
            android:id="@+id/contents"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="메모내용"
            android:lines="2"
            android:ellipsize="end"
            android:fontFamily="@font/kang"/>
    </LinearLayout>

</androidx.cardview.widget.CardView>

메모장메인

메모 insert

InsertAcitivy

public class InsertActivity extends AppCompatActivity {
    FirebaseUser user;
    FirebaseDatabase db;
    DatabaseReference ref;
    EditText contents;

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

        user = FirebaseAuth.getInstance().getCurrentUser();
        getSupportActionBar().setTitle("메모작성 | " + user.getEmail());
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        contents = findViewById(R.id.contents);

        db = FirebaseDatabase.getInstance();
        FloatingActionButton edit = findViewById(R.id.edit);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String strContents = contents.getText().toString();
                if (strContents.equals("")) {
                    Toast.makeText(InsertActivity.this,
                            "내용을 입력하세요!", Toast.LENGTH_SHORT).show();
                } else {
                    MemoVO vo = new MemoVO();
                    vo.setEmail(user.getEmail());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    vo.setDate(sdf.format(new Date()));
                    vo.setContents(strContents);
                    ref = db.getReference("memos").child(user.getUid()).push();
                    vo.setKey(ref.getKey());
                    ref.setValue(vo);
                    Toast.makeText(InsertActivity.this,
                            "저장완료!", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });
    }

        @Override
        public boolean onOptionsItemSelected (@NonNull MenuItem item){
            switch (item.getItemId()) {
                case android.R.id.home:
                    finish();
                    break;
            }
            return super.onOptionsItemSelected(item);
        }
    }

activity_insert

<?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=".InsertActivity">
    <EditText
        android:id="@+id/contents"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20sp"
        android:hint="메모내용"
        android:gravity="start"/>
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_edit"
        android:id="@+id/edit"
        android:backgroundTint="#E2D0F9"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_margin="10sp"
        app:borderWidth="0sp"/>
</RelativeLayout>

메모작성2

메모읽기, 메모 수정, 삭제

ReadActivity

public class ReadActivity extends AppCompatActivity {
    FirebaseUser user;
    MemoVO vo;
    EditText contents;
    FirebaseDatabase db;
    DatabaseReference ref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert);
        db= FirebaseDatabase.getInstance("https://my-project-c0f17-default-rtdb.firebaseio.com/");


        user= FirebaseAuth.getInstance().getCurrentUser();
        getSupportActionBar().setTitle("정보수정 | "+user.getEmail());
        getSupportActionBar().setDisplayShowTitleEnabled(true);

        Intent intent = getIntent();
        vo=(MemoVO)intent.getSerializableExtra("vo");
        System.out.println("read :" +vo.toString());

        contents= findViewById(R.id.contents);
        contents.setText(vo.getContents());

        FloatingActionButton edit =findViewById(R.id.edit);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strContent =contents.getText().toString();
                if(!vo.getContents().equals(strContent)){
                    AlertDialog.Builder box = new AlertDialog.Builder(ReadActivity.this);
                    box.setTitle("질의");
                    box.setMessage("변경된 내용을 수정하실래요?");
                    box.setPositiveButton("예", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //메모수정
                            vo.setContents(strContent);
                            SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            vo.setDate(sdf.format(new Date()));
                            ref=db.getReference("memos").child(user.getUid()+ "/"+vo.getKey());
                            ref.setValue(vo);
                            finish();
                        }
                    });
                    box.setNegativeButton("아니오", null);
                    box.show();
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch ( item.getItemId()){
            case android.R.id.home:
                finish();
                break;
            case R.id.delete:
                AlertDialog.Builder box = new AlertDialog.Builder(this);
                box.setTitle("질의");
                box.setMessage("메모를 삭제하실래요?");
                box.setPositiveButton("예", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ref=db.getReference("memos").child(user.getUid()+ "/"+vo.getKey());
                        ref.removeValue();
                        finish();
                    }
                });
                box.setNegativeButton("아니오",null);
                box.show();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.read, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

채팅

ChatActivity

public class ChatActivity extends AppCompatActivity {
    FirebaseUser user;
    FirebaseDatabase db;
    DatabaseReference ref;
    EditText contents;
    ArrayList<MemoVO> array = new ArrayList<>();
    ChatAdapter chatAdapter= new ChatAdapter();
    RecyclerView list;

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

        user = FirebaseAuth.getInstance().getCurrentUser();
        getSupportActionBar().setTitle("채팅 |" +user.getEmail());
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        db=FirebaseDatabase.getInstance();

        //채팅목록
        ref=db.getReference("chats");
        ref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                MemoVO vo = (MemoVO)snapshot.getValue(MemoVO.class);
                array.add(vo);
                System.out.println(vo.toString());
                chatAdapter.notifyDataSetChanged();
                list.scrollToPosition(array.size()-1);

            }

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

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {
                chatAdapter.notifyDataSetChanged();
            }

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

            }

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

            }
        });
        contents = findViewById(R.id.contents);

        list = findViewById(R.id.list);
        list.setAdapter(chatAdapter);
        list.setLayoutManager(new LinearLayoutManager(this));

        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{
                    //전송
                    MemoVO vo = new MemoVO();
                    vo.setEmail(user.getEmail());
                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    vo.setDate(sdf.format(new Date()));
                    vo.setContents(strContents);
                    ref=db.getReference("chats").push();
                    vo.setKey(ref.getKey());
                    ref.setValue(vo);
                    contents.setText("");
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //채팅 어댑터
    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 ChatAdapter.ViewHolder holder, int position) {
            MemoVO vo = array.get(position);
            holder.contents.setText(vo.getContents());
            holder.email.setText(vo.getEmail());
            holder.date.setText(vo.getDate());

            LinearLayout.LayoutParams paramsContents =
                    (LinearLayout.LayoutParams) holder.contents.getLayoutParams();
            LinearLayout.LayoutParams paramsDate =
                    (LinearLayout.LayoutParams) holder.date.getLayoutParams();

            if (vo.getEmail().equals(user.getEmail())) {//내가보낸메세지
                paramsContents.gravity = Gravity.RIGHT;
                paramsDate.gravity = Gravity.RIGHT;
                holder.email.setVisibility(View.GONE);
                holder.contents.setBackgroundResource(R.drawable.bubble);
                //내가보낸 메세지에서 롱클릭한 경우
                holder.contents.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.Builder box = new AlertDialog.Builder(ChatActivity.this);
                        box.setTitle("메뉴를 선택하세요!");
                        box.setItems(new String[]{"삭제", "취소"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(which==0){
                                    //삭제
                                    ref=db.getReference("chats").child(vo.getKey());
                                    ref.removeValue();
                                }
                            }
                        });
                        box.show();
                        return false;

                    }
                });
            } else {//다른사람메세지
                paramsContents.gravity = Gravity.LEFT;
                paramsDate.gravity = Gravity.LEFT;
                holder.contents.setBackgroundResource(R.drawable.left_bubble);
                holder.email.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView contents,date,email;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                contents=itemView.findViewById(R.id.contents);
                date=itemView.findViewById(R.id.date);
                email=itemView.findViewById(R.id.email);
            }
        }
    }
}

item_chat

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="10sp">
    <TextView
        android:id="@+id/contents"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="여기에는 글 내용이 출력됩니다."
        android:background="@drawable/bubble"
        android:padding="10sp"
        android:fontFamily="@font/kang"/>
    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="여기에는 글쓴 날짜"
        android:fontFamily="@font/kang"/>
    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="누가 썼나요 ?"
        android:fontFamily="@font/ho"
        android:textSize="10sp"/>
</LinearLayout>

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">
        <EditText
            android:id="@+id/contents"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10sp"
            android:hint="내용입력"/>
        <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"/>
    </RelativeLayout>
</LinearLayout>

채팅목록

끝!!

댓글남기기