mojo's Blog

안드로이드 프로그래밍 제 8장 연습문제 6번 본문

Android

안드로이드 프로그래밍 제 8장 연습문제 6번

_mojo_ 2021. 8. 31. 15:34

6번 ) 일기장을 내장 메모리가 아닌 SD 카드의 myDiary 폴더에 저장되도록 구현하기

 

XML Code

 

<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:gravity="center">
        <DatePicker
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:calendarViewShown="false"
            android:id="@+id/datePicker"/>
    </LinearLayout>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edit1"
        android:background="#00ff00"
        android:lines="8"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="새로 저장"
        android:enabled="false"
        android:id="@+id/btn1"/>

</LinearLayout>

 

Java Code

 

public class MainActivity extends AppCompatActivity {
    DatePicker dp;
    EditText edit;
    Button btn;
    String fileName;
    File[] fileNames;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("연습하기");

        ActivityCompat.requestPermissions(this, new String[]
                {Manifest.permission.WRITE_EXTERNAL_STORAGE}, MODE_PRIVATE);

        dp = (DatePicker)findViewById(R.id.datePicker);
        edit = (EditText)findViewById(R.id.edit1);
        btn = (Button)findViewById(R.id.btn1);

        fileNames = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/myDiary").listFiles();

        Calendar cal = Calendar.getInstance();
        int cYear = cal.get(Calendar.YEAR);
        int cMonth = cal.get(Calendar.MONTH);
        int cDay = cal.get(Calendar.DAY_OF_MONTH);

        dp.init(cYear, cMonth, cDay, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
                fileName = Environment.getExternalStorageDirectory().getAbsolutePath()+"/myDiary/" +
                        Integer.toString(year)+"_"+Integer.toString(month+1)+"_"+Integer.toString(day) + ".txt";
                String str = readDiary(fileName);
                edit.setText(str);
                btn.setEnabled(true);
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    FileOutputStream outFs = new FileOutputStream(fileName);
                    String str = edit.getText().toString();
                    outFs.write(str.getBytes());
                    outFs.close();
                    Toast.makeText(getApplicationContext(), fileName+" 이 저장됨", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    Toast.makeText(getApplicationContext(), "에러입니다.", Toast.LENGTH_SHORT).show();
                }
                fileNames = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/myDiary").listFiles();
            }
        });

    }

    String readDiary(String s){
        String ret = null;

        for(int i=0; i<fileNames.length; i++){
            if(fileNames[i].toString().equals(s)){
                try{
                    FileInputStream inFs = new FileInputStream(s);
                    byte[] txt = new byte[inFs.available()];
                    inFs.read(txt);
                    inFs.close();
                    ret = new String(txt);
                    btn.setText("수정하기");
                    return ret;
                } catch(IOException e){
                    Toast.makeText(getApplicationContext(), "오류입니다.", Toast.LENGTH_SHORT).show();
                }
            }
        }

        edit.setHint("일기 없음");
        btn.setText("새로 저장");
        return ret;
    }
}

 

'Android' 카테고리의 다른 글

Bitmap  (0) 2021.09.02
Graphic  (0) 2021.09.02
파일 처리 및 응용  (0) 2021.08.31
안드로이드 프로그래밍 제 7장 연습문제 (4, 5, 6번)  (0) 2021.08.30
대화상자  (0) 2021.08.30
Comments