Programming/국비학원

220526 - 안드로이드 구현 실습 (투표, 다이어리)

지고르 2022. 5. 30. 11:30
명화 투표 (계속)

인기 1위 그림, 이름 resultActivity 화면에 띄우기

 

※code-override methods : 메소드 종류 확인

 

  • 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic1" />
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic2"/>
        <ImageView
            android:id="@+id/img3"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic3"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">
        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic4"/>
        <ImageView
            android:id="@+id/img5"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic5"/>
        <ImageView
            android:id="@+id/img6"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic6"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">
        <ImageView
            android:id="@+id/img7"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic7"/>
        <ImageView
            android:id="@+id/img8"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic8"/>
        <ImageView
            android:id="@+id/img9"
            android:layout_width="wrap_content"
            android:layout_height="130dp"
            android:layout_weight="1"
            android:layout_margin="5dp"
            android:src="@drawable/pic1"/>
    </LinearLayout>

    <Button
        android:id="@+id/btnVoteResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="투표 종료"/>

</LinearLayout>

 

 

  • xml : 2

<?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"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".ResultActivity">

    <TextView
        android:id="@+id/tvTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        />

    <ImageView
        android:id="@+id/imgTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="명화 이름1"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="명화 이름2"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="명화 이름3"
            android:layout_weight="1"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="명화 이름4"
            android:layout_weight="1"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName5"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="명화 이름5"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="명화 이름6"
            android:layout_weight="1"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="명화 이름7"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar7"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="명화 이름8"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tvName9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="명화 이름9"
            android:textSize="16dp"/>

        <RatingBar
            android:id="@+id/rBar9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            style= "?android:attr/ratingBarStyleSmall"
            />
    </LinearLayout>

    <Button
        android:id="@+id/btnReturn"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="메인으로 돌아가기"
        />

</LinearLayout>

 

 

  • java : 메인

package com.hk.myapplication;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
    Button btnVoteResult;
    ImageView[] imgs = new ImageView[9];
    Integer[] imgsID = {R.id.img1, R.id.img2,R.id.img3,R.id.img4,R.id.img5,R.id.img6,R.id.img7,R.id.img8,R.id.img9};
    String[] imgName = {"a","b","c","d","e","f","g","h","i"};
    int[] voteCount = new int[9];  //각 명화 투표 수
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnVoteResult = findViewById(R.id.btnVoteResult);
        for (int i=0;i<imgs.length;i++){
            imgs[i]=findViewById(imgsID[i]);
        }
        //이미지 클릭
        for (int i=0;i<imgs.length;i++) {
            final int index= i;  //final 처리
            imgs[index].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    voteCount[index]++;
                    Toast.makeText(getApplicationContext(), imgName[index] + " : 총 " + voteCount[index] + "표",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        //투표 종료 버튼
        btnVoteResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
                //지금 코드 맥락에서 ResultActivity 클래스와 연결
                intent.putExtra("VoteCount",voteCount);
                intent.putExtra("ImgName",imgName);
                //전달할 변수: 대문자  //배열 전체 전달
                startActivity(intent);
            }
        });

    }//oncreate
}

 

 

  • java : 2

package com.hk.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

public class ResultActivity extends AppCompatActivity {
    Button btnReturn;
    TextView tvName[] = new TextView[9];
    Integer tvNameID[] = {R.id.tvName1,R.id.tvName2,R.id.tvName3,R.id.tvName4,
            R.id.tvName5,R.id.tvName6,R.id.tvName7,R.id.tvName8,R.id.tvName9};
    RatingBar rBar[] = new RatingBar[9];
    Integer rBarID[] = {R.id.rBar1,R.id.rBar2,R.id.rBar3,R.id.rBar4,
            R.id.rBar5,R.id.rBar6,R.id.rBar7,R.id.rBar8,R.id.rBar9};
    int[] voteResult;  //투표 수 배열
    String[] imgNames; //명화 이름 배열
    TextView tvTop;
    ImageView imgTop;
    Integer[] imgDraw = {R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,
            R.drawable.pic4,R.drawable.pic5,R.drawable.pic6,R.drawable.pic7,R.drawable.pic8,R.drawable.pic9};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        btnReturn = findViewById(R.id.btnReturn);
        for (int i=0;i<tvName.length;i++){
            tvName[i]=findViewById(tvNameID[i]);
        }
        for (int i=0;i<rBar.length;i++){
            rBar[i]=findViewById(rBarID[i]);
        }
        tvTop = findViewById(R.id.tvTop);
        imgTop = findViewById(R.id.imgTop);
        //선언

        Intent gintent = getIntent();
        voteResult = gintent.getIntArrayExtra("VoteCount");
        imgNames = gintent.getStringArrayExtra("ImgName");

        int max=0; //최고 투표수 있는 배열의 인덱스
        for (int i = 1;i<tvName.length;i++){
            if (voteResult[max]<voteResult[i]) {
                max=i;
            };
        }

        tvTop.setText("최고의 명화 "+imgNames[max]);
        imgTop.setImageResource(imgDraw[max]);

        for (int i=0;i<voteResult.length;i++){
            tvName[i].setText(imgNames[i]+" (총 "+voteResult[i]+"표)");
            rBar[i].setRating(voteResult[i]);
        }

        btnReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
}

 

 

 

※ 액티비티 생명주기

 

onCreate, onStart, onResume, onPause, onStop, onDestroy 등 다양한 액티비티 사이클로 구성됨

 

 

  •  

package com.hk.multiactivity;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
    Button btnNewActivity, btnFinish;
    EditText edtKor, edtEng;
    int kor, eng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i("test","onCreate 메서드 수행했음");

        edtKor = findViewById(R.id.edtKor);
        edtEng = findViewById(R.id.edtEng);
        btnNewActivity = findViewById(R.id.btnNewActivity);
        btnFinish = findViewById(R.id.btnFinish);

        //버튼을 누르면 새 activity 호출
        btnNewActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                kor = Integer.parseInt(edtKor.getText().toString());
                eng = Integer.parseInt(edtEng.getText().toString());
                Intent mIntent = new Intent(getApplicationContext(), NewActivity.class); //(장소, 호출할 activity)
                mIntent.putExtra("korScore",kor);
                mIntent.putExtra("engScore",eng);
                startActivity(mIntent);
            }
        });

        //앱 종료
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }//oncreate

    @Override
    protected void onStart() {
        super.onStart();
        Log.i("test","onStart 메서드 수행했음");
    }//onstart

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("test","onResume 메서드 수행했음");
    }//onresume

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("test","onPause 메서드 수행했음");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("test","onStop 메서드 수행했음");

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i("test","onRestart 메서드 수행했음");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("test","onDestroy 메서드 수행했음");
    }

}

 

=> 실행 후 로그 확인 => 메인화면에서 onStart, onResume 실행되다가 결과화면 넘어갈 때 onPause, onStop, 다시 메인화면 복귀 시 onRestart, 종료 시 onStop, onDestroy

 

 

=>

  • 투표 메인 자바파일 수정 (전날 질문 반영, 메인화면 돌아올 때 voteCount 초기화)

package com.hk.myapplication;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
    Button btnVoteResult;
    ImageView[] imgs = new ImageView[9];
    Integer[] imgsID = {R.id.img1, R.id.img2,R.id.img3,R.id.img4,R.id.img5,R.id.img6,R.id.img7,R.id.img8,R.id.img9};
    String[] imgName = {"a","b","c","d","e","f","g","h","i"};
    int[] voteCount = new int[9];  //각 명화 투표 수
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnVoteResult = findViewById(R.id.btnVoteResult);
        for (int i=0;i<imgs.length;i++){
            imgs[i]=findViewById(imgsID[i]);
        }
        //이미지 클릭
        for (int i=0;i<imgs.length;i++) {
            final int index= i;  //final 처리
            imgs[index].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    voteCount[index]++;
                    Toast.makeText(getApplicationContext(), imgName[index] + " : 총 " + voteCount[index] + "표",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        //투표 종료 버튼
        btnVoteResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),ResultActivity.class);
                //지금 코드 맥락에서 ResultActivity 클래스와 연결
                intent.putExtra("VoteCount",voteCount);
                intent.putExtra("ImgName",imgName);
                //전달할 변수: 대문자  //배열 전체 전달
                startActivity(intent);
            }
        });

    }//oncreate

    @Override    
    protected void onResume() {
        super.onResume();
        for (int i=0;i<voteCount.length;i++){
            voteCount[i]=0;
        }
    }
}

 

 

 

다이어리

저장 버튼 => 2022_05_25 날짜로 파일 이름 저장
일기 없는 날짜 클릭 => 일기없음 표시
일기 있으면 수정버튼

 

 

  • 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"
    android:orientation="vertical"
    android:padding="10dp"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

    <CalendarView
        android:id="@+id/calView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <EditText
        android:id="@+id/edtDiary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:lines="10"
        android:layout_weight="1"
        android:gravity="left|top"
        android:background="#D9E5FF"/>

    <Button
        android:id="@+id/btnSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="저장"/>

</LinearLayout>

 

 

 

  • java : 날짜 미선택 되어도 일기 표시

package com.hk.diary;

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

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

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    CalendarView calView;
    EditText edtDiary;
    Button btnSave;
    String fileName;  //저장할 파일 이름
    String content;  //Edittext 내용 담을 변수

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        calView = findViewById(R.id.calView);
        edtDiary = findViewById(R.id.edtDiary);
        btnSave = findViewById(R.id.btnSave);

        //앱 실행 시 날짜 미선택되어도 오늘 일기 표시
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH)+1;
        int day = now.get(Calendar.DAY_OF_MONTH);
        String fileName2 = year + "_" + month + "_" + day + ".txt";
        try {
            FileInputStream fileis = openFileInput(fileName2);
            byte[] strB = new byte[fileis.available()];
            fileis.read(strB);
            edtDiary.setText(new String(strB).trim());
            fileis.close();
        } catch (IOException e) {
            edtDiary.setHint("일기 없음");
            edtDiary.setText("");
        }

        //달력 날짜 선택
        calView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override  //날짜 선택 필수
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) { //month는 +1
                fileName = year + "_" + (month+1) + "_" + dayOfMonth + ".txt";
                try {
                    FileInputStream fileis = openFileInput(fileName);  //존재하는 파일 불러옴
                    byte[] strB = new byte[fileis.available()];  //입력한 만큼 strB 배열에 전달
                    fileis.read(strB);
                    edtDiary.setText(new String(strB).trim());
                    fileis.close();
                } catch (IOException e) {
                    edtDiary.setHint("일기 없음");
                    edtDiary.setText("");  //설정해야지 hint도 실행
                }
            }
        });
        
        //저장 버튼
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //FileOutputStream fileos = new FileOutputStream();
                try {  //입출력은 try, catch 필수
                    FileOutputStream fileos = openFileOutput(fileName,MODE_PRIVATE);
                    //MODE_APPEND : 있는 파일에 추가 저장 / PRIVATE : 새로 저장
                    content = edtDiary.getText().toString();
                    fileos.write(content.getBytes());
                    fileos.close();  //필수
                    Toast.makeText(getApplicationContext(),fileName+"가 저장되었습니다",Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),"파일을 저장할 수 없습니다",Toast.LENGTH_SHORT).show();
                }
            }
        });//btnSave

    }//onCreate
}

 

 

  • java : 날짜 미선택 관련 메소드 축약 => 새 메소드 생성

package com.hk.diary;

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

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

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    CalendarView calView;
    EditText edtDiary;
    Button btnSave;
    String fileName;  //저장할 파일 이름
    String content;  //Edittext 내용 담을 변수


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

        calView = findViewById(R.id.calView);
        edtDiary = findViewById(R.id.edtDiary);
        btnSave = findViewById(R.id.btnSave);

        //앱 실행 시 날짜 미선택되어도 오늘 일기 표시
        Calendar now = Calendar.getInstance();
        int cyear = now.get(Calendar.YEAR);
        int cmonth = now.get(Calendar.MONTH)+1;
        int cday = now.get(Calendar.DAY_OF_MONTH);
        fileName = cyear + "_" + cmonth + "_" + cday + ".txt";
        content=readDiary(fileName);
        edtDiary.setText(content);

        //달력 날짜 선택
        calView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override  //날짜 선택 필수
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) { //month는 +1
                fileName = year + "_" + (month+1) + "_" + dayOfMonth + ".txt";
                content=readDiary(fileName);
                edtDiary.setText(content);
            }
        });
        
        //저장 버튼
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //FileOutputStream fileos = new FileOutputStream();
                try {  //입출력은 try, catch 필수
                    FileOutputStream fileos = openFileOutput(fileName,MODE_PRIVATE);
                    //MODE_APPEND : 있는 파일에 추가 저장 / PRIVATE : 새로 저장
                    content = edtDiary.getText().toString();
                    fileos.write(content.getBytes());
                    fileos.close();  //필수
                    Toast.makeText(getApplicationContext(),fileName+"가 저장되었습니다",Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(),"파일을 저장할 수 없습니다",Toast.LENGTH_SHORT).show();
                }
            }
        });//btnSave

    }//onCreate

    //일기 읽어오는 메소드
    String readDiary(String fileName){
        String diaryStr = null;
        try {
            FileInputStream fileis = openFileInput(fileName);
            byte[] strB = new byte[fileis.available()];
            fileis.read(strB);
            //edtDiary.setText(new String(strB).trim());
            diaryStr = new String(strB).trim();
            fileis.close();
        } catch (IOException e) {
            edtDiary.setHint("일기 없음");
            edtDiary.setText("");
        }
        return diaryStr;  //일기 내용 또는 "일기 없음" 불러옴
    }
    
}

 

 

 

 

//

점점 안드로이드 구현이 재밌어진당