본문 바로가기
ICIA 수업일지

2021.09.30 수업일지(안드로이드 개발 기초, Firebase)

by 주성씨 2021. 9. 30.

- 파이어베이스를 이용해서 DB를 활용할 수 있도록 하겠다. object로 이뤄진 DB를 제공해준다. 구글에서 서비스한다.

- build.gradle -  version 수정

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30 <<<---
    buildToolsVersion "30.0.0" <<<---

    defaultConfig {
        applicationId "com.example.ex06"
        minSdkVersion 26 <<<---
        targetSdkVersion 30 <<<---
        versionCode 1 
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.android.support:design:30.0.0' <<<---
}

 

확인

 

- 메모장 어플을 만들어보도록 하겠다.

- 사용자에 따라서 로그인(인증)을 통해 개별 메모장을 가질 수 있도록 하겠다.

- 파이어베이스를 통해서 인증작업을 하도록 하겠다.

 

- Authentication click -> Email and password authentication click -> 1. connect to Firebase -> google account login -> android studio login fin 

콘솔로 이동

 

파이어베이스 시작

 

새로운 프로젝트 새성

 

로그인 인증방법 설정
accept changes click

 

적용 및 다운로드 확인

 

- build.gradle - 파이어베이스 설치 확인

.....
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    implementation 'com.google.firebase:firebase-auth:16.0.5' <<<---
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.android.support:design:30.0.0'
}

 

 

프로젝트 신규 앱 등록

 

앱 패키지 네임과 앱 닉네임 설정

 

 

다운받은 데이터 경로

 

다음 다음 다음 후 아래

 

설정 끝 확인

 

앱 추가 확인

 

권한 및 사용자 확인 아직 사용자 추가는 안한다.

 

 

- 로그인 화면을 꾸며보도록 하겠다.

- src/main/res/layout/activity_main.xml

<?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:orientation="vertical"
    android:gravity="center"
    android:padding="30sp">

    <EditText
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Email"/>
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="password"/>
    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"/>
    <Button
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"/>
</LinearLayout>

 

확인

 

- 이제 버튼을 클릭속성을 지정하여 특정 메서드를 실행하도록 하겠다.

.....
    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:onClick="mClick"/>
    <Button
        android:id="@+id/register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:onClick="mClick"/>
</LinearLayout>

 

- 메서드를 생성하겠다.

- src/main/java/com/example/ex06/MainActivity.java

package com.example.ex06;

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

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {
    // 값을 가지고 오기 위한 전역변수
    EditText email, password;
    // 회원등록을 위한 firebaseauth
    FirebaseAuth mAuth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 값 가지고 오기
        email = findViewById(R.id.email);
        password = findViewById(R.id.password);

        mAuth = FirebaseAuth.getInstance();

        getSupportActionBar().setTitle("로그인");

    }
    // View는 모든 위젯의 상위
    public void mClick(View v){

        String strEmail = email.getText().toString();
        String strPassword = password.getText().toString();

        switch (v.getId()){
            case R.id.login:
                break;
            case R.id.register:
                // 유저생성을 위한 메서드
                mAuth.createUserWithEmailAndPassword(strEmail, strPassword)
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){
                            Toast.makeText(MainActivity.this,"등록성공",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(MainActivity.this,"등록실패",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
        }
    }
}

 

파이어베이스에서 확인할 수 있다.

 

- password 입력시 안보이게 하겠다.

- src/main/java/com/example/ex06/MemoActivity.java

.....
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="password"
        android:password="true"
        android:text="12341234"/>
.....

 

- 이제 해당 계정을 가지고 로그인 하는 작업을 하도록 하겠다.

- src/main/java/com/example/ex06/MainActivity.java

.....
    // View는 모든 위젯의 상위
    public void mClick(View v){

        String strEmail = email.getText().toString();
        String strPassword = password.getText().toString();

        switch (v.getId()){
            case R.id.login:
                mAuth.signInWithEmailAndPassword(strEmail,strPassword)
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(MainActivity.this,"로그인성공",Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(MainActivity.this,"로그인실패",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                break;
.....

 

 

- src/main/java/com/example/ex06/MemoActivity.java

package com.example.ex06;

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

import android.os.Bundle;
import android.view.MenuItem;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MemoActivity extends AppCompatActivity {
    FirebaseUser user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memo);

        // 현재 로그인 유저 정보
        user = FirebaseAuth.getInstance().getCurrentUser();
        String email = user.getEmail(); // 해당 유저의 이메일

        getSupportActionBar().setTitle(email);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

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

 

- src/main/java/com/example/ex06/(new)MemoActivity.java

.....
    // View는 모든 위젯의 상위
    public void mClick(View v){

        String strEmail = email.getText().toString();
        String strPassword = password.getText().toString();

        switch (v.getId()){
            case R.id.login:
                mAuth.signInWithEmailAndPassword(strEmail,strPassword)
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if(task.isSuccessful()){
                                    Intent intent = new Intent(MainActivity.this, MemoActivity.class);
                                    startActivity(intent);
                                }else{
                                    Toast.makeText(MainActivity.this,"로그인실패",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                break;
.....

 

확인

 

 

- 이제 메모장의 CRUD 작업을 하겠다.

- 리얼타임 DB 라이브러리를 추가하겠다.

Tools -> Firebase

 

Add -> accept

 

설치 후 Firebase 홈에서 확인

 

잠금모드로 시작 후 사용 설정

 

규칙을 true로 변경하고 위에 게시를 클릭하여 적용

 

데이터가 오브젝트 형식으로 저장되어 있다.

 

- build.gradle - > 라이브러리 확인

.....
dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4' <<<---
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.android.support:design:30.0.0'
}

 

- 이제 입력프로그램을 만들겠다.

- src/main/res/drawable/(new)ic_write.xml

- src/main/res/layout/activity_memo.xml

<?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">
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/write"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20sp"
        android:layout_marginRight="20sp"
        android:backgroundTint="#E91E63"
        android:src="@drawable/ic_write"/>
</RelativeLayout>

 

-src/main/java/com/example/ex06/(new)WriteActivity.java

package com.example.ex06;

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

import android.os.Bundle;
import android.view.MenuItem;

public class WriteActivity extends AppCompatActivity {

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

        getSupportActionBar().setTitle("메모작성");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

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

 

- src/main/java/com/example/ex06/MemoActivity.java

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

        // 현재 로그인 유저 정보
        user = FirebaseAuth.getInstance().getCurrentUser();
        String email = user.getEmail(); // 해당 유저의 이메일

        getSupportActionBar().setTitle(email);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FloatingActionButton write = findViewById(R.id.write); <<<---
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MemoActivity.this, WriteActivity.class);
                startActivity(intent);
            }
        });

    }
.....

 

 

 

- src/main/res/layout/activity_write.xml

<?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=".WriteActivity">
    <EditText
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:hint="내용을 입력하세요."
        android:padding="20sp"
        android:textSize="20sp"
        android:gravity="top"
        android:background="@null"/>
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/write"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20sp"
        android:layout_marginRight="20sp"
        android:backgroundTint="#E91E63"
        app:borderWidth="0sp"
        android:src="@drawable/ic_write"/>
</RelativeLayout>

 

확인

 

 

- 메모를 작성하고 DB에 저장하도록 하겠다.

- src/main/java/com/example/ex06/(new)Memo.java - java class

package com.example.ex06;

public class Memo {
    private String key;
    private String content;
    private String createDate;
    private String updateDate;
.....
getter and setter
toSring

 

- src/main/java/com/example/ex06/WriteActivity.java

.....
public class WriteActivity extends AppCompatActivity {
    EditText content; <<<----
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write);

        getSupportActionBar().setTitle("메모작성");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        content = findViewById(R.id.content); <<<----
        FloatingActionButton write = findViewById(R.id.write);
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String strContent = content.getText().toString();
                if(strContent.equals("")){
                    AlertDialog.Builder box = new AlertDialog.Builder(WriteActivity.this);
                    box.setMessage("내용을 입력하세요.");
                    box.setPositiveButton("닫기",null);
                    box.show();
                }else{
                    Memo memo = new Memo();
                    memo.setContent(strContent);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    memo.setCreateDate(sdf.format(new Date()));
                    System.out.println(memo.toString());
                }
            }
        });

    }
.....

 

콘솔에 찍어보았다.

 

- 이제 DB에 넣어보자.

.....
public class WriteActivity extends AppCompatActivity {
    EditText content;

    // DB에 저장하기 위한 유저정보 가지고 오기 <<<---
    FirebaseAuth mAuth;
    FirebaseDatabase db;
    DatabaseReference mRef;
    FirebaseUser user;

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

        mAuth = FirebaseAuth.getInstance(); <<<---
        user = mAuth.getCurrentUser(); <<<---

        getSupportActionBar().setTitle("메모작성");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        content = findViewById(R.id.content);
        FloatingActionButton write = findViewById(R.id.write);
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String strContent = content.getText().toString();
                AlertDialog.Builder box;
                if(strContent.equals("")){
                    box = new AlertDialog.Builder(WriteActivity.this);
                    box.setMessage("내용을 입력하세요.");
                    box.setPositiveButton("닫기",null);
                    box.show();
                }else{ <<<---
                    Memo memo = new Memo();
                    memo.setContent(strContent);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    memo.setCreateDate(sdf.format(new Date()));
                    System.out.println(memo.toString());
                    box = new AlertDialog.Builder(WriteActivity.this);
                    box.setMessage("내용을 저장하시겠습니까?");
                    box.setNegativeButton("아니오",null);
                    box.setPositiveButton("예", null);
                    box.show();
                }
            }
        });

    }
.....

 

확인

 

- 혹시 데이터가 안들어가고 오류가 발생한다며 아래의 페이지에서 안내하는대로 해보자.

https://simpleneed.tistory.com/74

 

유니티 Firebase 연동 에러 DatabaseException: Failed to get FirebaseDatabase instance: Specify DatabaseURL within Firebase

유니티와 Firebase 연동 중 아래와 같은 에러가 났다. DatabaseException: Failed to get FirebaseDatabase instance: Specify DatabaseURL within FirebaseApp or from your GetInstance() call. 해결 방법 1. F..

simpleneed.tistory.com

 

- DB에 다른 계정 2개로 데이터가 들어가는지 확인해보자.

.....
public class WriteActivity extends AppCompatActivity {
    EditText content;
    FirebaseAuth mAuth;
    FirebaseDatabase db;
    DatabaseReference mRef;
    FirebaseUser user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write);

        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        db = FirebaseDatabase.getInstance(); <<<----

        getSupportActionBar().setTitle("메모작성");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        content=findViewById(R.id.content);
        FloatingActionButton write=findViewById(R.id.write);
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strContent = content.getText().toString();
                if(strContent.equals("")){
                    AlertDialog.Builder box=new AlertDialog.Builder(WriteActivity.this);
                    box.setMessage("내용을 입력하세요!");
                    box.setPositiveButton("닫기", null);
                    box.show();
                }else {
                    Memo memo = new Memo();
                    memo.setContent(strContent);
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    memo.setCreateDate(sdf.format(new Date()));
                    System.out.println(memo.toString());
                    AlertDialog.Builder box=new AlertDialog.Builder(WriteActivity.this);
                    box.setMessage("내용을 저장하실래요");
                    box.setPositiveButton("예", new DialogInterface.OnClickListener() {  <<<----
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mRef = db.getReference("memos").child(user.getUid()).push();
                            mRef.setValue(memo);
                            finish();
                        }
                    });
                    box.setNeutralButton("아니오", null);
                    box.show();
                }
            }
        });
    }
.....

 

확인

 

- 이제 memo 액티비티를 꾸미고 해당 액티비티에 들어갈 아이템 레이아웃을 만들자.

- src/main/res/layout/(new)item_memo.xml

<?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="match_parent"
    android:orientation="vertical"
    android:padding="20sp">
    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="여기에는 메모가 출력됩니다."
        android:lines="1"
        android:ellipsize="end"
        android:textSize="25sp"/>
    <TextView
        android:id="@+id/createDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="여기에는 날짜가 출력"
        android:textSize="15sp" />
</LinearLayout>

 

- src/main/java/com/example/ex06/MemoActivity.java

.....
public class MemoActivity extends AppCompatActivity {

    MemoAdapter memoAdapter = new MemoAdapter();  <<<<----
    ArrayList<Memo> array = new ArrayList<>();  <<<<----
    ListView list;  <<<<----
    FirebaseDatabase database;  <<<<----
    FirebaseUser user;
    DatabaseReference ref;  <<<<----

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

        list  = findViewById(R.id.list);

        // 현재 로그인 유저 정보
        user = FirebaseAuth.getInstance().getCurrentUser();
        String email = user.getEmail(); // 해당 유저의 이메일

        getSupportActionBar().setTitle(email);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FloatingActionButton write = findViewById(R.id.write);
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MemoActivity.this, WriteActivity.class);
                startActivity(intent);
            }
        });

        // 생성시 데이터를 가지고옴 
        // memos 아래 user id의 데이터를 가지고옴
        database = FirebaseDatabase.getInstance();  <<<<----
        ref = database.getReference("memos/"+user.getUid());  <<<<----
        ref.addChildEventListener(new ChildEventListener() {  <<<<----
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Memo memo = (Memo)dataSnapshot.getValue(Memo.class);
                memo.setKey(dataSnapshot.getKey());
                array.add(memo);
                list.setAdapter(memoAdapter);
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

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

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

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

            }
        });

    }

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

    class MemoAdapter extends BaseAdapter{ <<<<----

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

        @Override
        public Object getItem(int i) {
            return null;
        }

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.item_memo,viewGroup,false);
            Memo memo = array.get(i);
            TextView content = view.findViewById(R.id.content);
            content.setText(memo.getContent());
            TextView createDate = view.findViewById(R.id.createDate);
            createDate.setText(memo.getCreateDate());
            return view;
        }
    }
}

 

확인

 

- 리드 작업을 할 수 있는 리드 엑티비티를 생성하겠다.

- src/main/java/com/example/ex06/(new)ReadActivity.java

package com.example.ex06;

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

import android.os.Bundle;
import android.view.MenuItem;

public class ReadActivity extends AppCompatActivity {

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

        getSupportActionBar().setTitle("메모정보");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

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

 

- src/main/res/layout/item_memo.xml

<?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="match_parent"
    android:orientation="vertical"
    android:padding="20sp"
    android:id="@+id/item"> <<<---
.....

 

- src/main/java/com/example/ex06/MemoActivity.java

.....
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.item_memo,viewGroup,false);
            Memo memo = array.get(i);
            LinearLayout item = view.findViewById(R.id.item);
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MemoActivity.this, ReadActivity.class);
                    intent.putExtra("key", memo.getKey());
                    intent.putExtra("content",memo.getContent());
                    intent.putExtra("createDate",memo.getCreateDate());
                    intent.putExtra("updateDate",memo.getUpdateDate());
                    startActivity(intent);
                }
            });
            TextView content = view.findViewById(R.id.content);
            content.setText(memo.getContent());
            TextView createDate = view.findViewById(R.id.createDate);
            createDate.setText(memo.getCreateDate());
            return view;
        }
    }
}

 

- src/main/java/com/example/ex06/ReadActivity.java

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

        getSupportActionBar().setTitle("메모정보");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        String key = intent.getStringExtra("key");
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!"+key);
    }
.....

 

확인

 

- src/main/java/com/example/ex06/ReadActivity.java

public class ReadActivity extends AppCompatActivity {
    FirebaseDatabase database;
    DatabaseReference ref;
    Memo memo = new Memo();
    EditText content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write);

        content = findViewById(R.id.content);

        getSupportActionBar().setTitle("메모정보");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        String key = intent.getStringExtra("key");
        memo.setKey(intent.getStringExtra("key"));
        memo.setContent(intent.getStringExtra("content"));
        memo.setCreateDate(intent.getStringExtra("createDate"));
        memo.setUpdateDate(intent.getStringExtra("updateDate"));
        System.out.println(memo.toString());
        content.setText(memo.getContent());

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        database = FirebaseDatabase.getInstance();
        ref = database.getReference("memos/"+user.getUid()+"/"+key);
    }

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

 

확인

 

- 이제 정보를 수정하겠다.

- src/main/java/com/example/ex06/ReadActivity.java

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

        content = findViewById(R.id.content);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Intent intent = getIntent();
        String key = intent.getStringExtra("key");
        memo.setKey(intent.getStringExtra("key"));
        memo.setContent(intent.getStringExtra("content"));
        memo.setCreateDate(intent.getStringExtra("createDate"));
        memo.setUpdateDate(intent.getStringExtra("updateDate"));
        System.out.println(memo.toString());
        content.setText(memo.getContent());
        getSupportActionBar().setTitle("메모정보 / 작성일 : "+memo.getCreateDate());

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        database = FirebaseDatabase.getInstance();
        ref = database.getReference("memos/"+user.getUid()+"/"+key);

        FloatingActionButton write = findViewById(R.id.write); <<<---
        write.setOnClickListener(new View.OnClickListener() { <<<---
            @Override
            public void onClick(View view) {
                AlertDialog.Builder box = new AlertDialog.Builder(ReadActivity.this);
                box.setMessage("수정하시겠습니까?");
                box.setPositiveButton("예", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        memo.setContent(content.getText().toString());
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        memo.setUpdateDate(df.format(new Date()));
                        ref.setValue(memo);
                        finish();
                    }
                });
                box.setNegativeButton("아니오",null);
                box.show();
            }
        });
    }
.....

 

- src/main/java/com/example/ex06/MemoActivity.java

.....
    @Override
    protected void onRestart() {
        super.onRestart();
        readMemos();
    }

    public void readMemos(){
        array.clear();
        ref.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Memo memo = (Memo)dataSnapshot.getValue(Memo.class);
                memo.setKey(dataSnapshot.getKey());
                array.add(memo);
                memoAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

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

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

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

            }
        });
    }
}

 

- src/main/res/layout/item_memo.xml

.....
    <TextView
        android:id="@+id/updateDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="여기에는 수정날짜가 출력"
        android:textSize="15sp" />
</LinearLayout>

 

- src/main/java/com/example/ex06/MemoActivity.java

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

        list  = findViewById(R.id.list);
        list.setAdapter(memoAdapter);

        // 현재 로그인 유저 정보
        user = FirebaseAuth.getInstance().getCurrentUser();
        String email = user.getEmail(); // 해당 유저의 이메일

        getSupportActionBar().setTitle(email);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        FloatingActionButton write = findViewById(R.id.write);
        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MemoActivity.this, WriteActivity.class);
                startActivity(intent);
            }
        });

        // 생성시 데이터를 가지고옴
        // memos 아래 user id의 데이터를 가지고옴
        database = FirebaseDatabase.getInstance();
        ref = database.getReference("memos/"+user.getUid());
        readMemos(); <<<---
    }
.....
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.item_memo,viewGroup,false);
            Memo memo = array.get(i);
            LinearLayout item = view.findViewById(R.id.item);
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MemoActivity.this, ReadActivity.class);
                    intent.putExtra("key", memo.getKey());
                    intent.putExtra("content",memo.getContent());
                    intent.putExtra("createDate",memo.getCreateDate());
                    intent.putExtra("updateDate",memo.getUpdateDate());
                    startActivity(intent);
                }
            });
            TextView content = view.findViewById(R.id.content);
            content.setText(memo.getContent());
            TextView createDate = view.findViewById(R.id.createDate);
            createDate.setText(memo.getCreateDate());
            TextView updateDate = view.findViewById(R.id.updateDate); <<<---
            updateDate.setText(memo.getUpdateDate());
            return view;
        }
.....

 

 

- 삭제 하도록 하겠다.

- src/main/res/(new)menu/(new)read.xml - android resources file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/delete"
        android:title="삭제"
        android:icon="@drawable/ic_baseline_delete_24"
        app:showAsAction="always"/>
</menu>

 

- src/main/java/com/example/ex06/ReadActivity.java

.....
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.delete: <<<---
                AlertDialog.Builder box = new AlertDialog.Builder(this);
                box.setMessage("삭제하시겠습니까?");
                box.setNegativeButton("아니오", null);
                box.setPositiveButton("예", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ref.removeValue();
                        finish();
                    }
                });
                box.show();
                break;
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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