초간단 메모장 만들기2 (파일변경)
http://lopicit.tistory.com/252
** 초간단 메모장 만들기1에 이어서 ***
이전 초간단 메모장 예제는 하나의 파일에 읽고 쓰고 삭제할 수 있었습니다.
이번에는 AlertDialog를 이용하여 다양한 파일을 불러와 읽고 쓰고 삭제할 수 있도록 만들어 보았습니다.
** 변경된 이벤트 리스너
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.load:
Log.i("TAG", "load 진행");
LinearLayout alert_layout1 = (LinearLayout) View.inflate(MainAc.this, R.layout.alert_layout, null);
final EditText alert_edit = (EditText) alert_layout1.findViewById(R.id.search_memo);
new AlertDialog.Builder(MainAc.this)
.setTitle("메모 불러오기")
.setMessage("불러올 메모")
.setView(alert_layout1)
.setPositiveButton("Load", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
filename = alert_edit.getText().toString();
Log.i("TAG", filename);
load(filename);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainAc.this,"Load 취소",Toast.LENGTH_SHORT).show();
}
}).show();
break;
case R.id.save:
Log.i("TAG", "save 진행");
LinearLayout alert_layout2 = (LinearLayout) View.inflate(MainAc.this, R.layout.alert_layout, null);
final EditText alert_edit2 = (EditText) alert_layout2.findViewById(R.id.search_memo);
if(filename == null){
new AlertDialog.Builder(MainAc.this)
.setTitle("메모 저장하기")
.setMessage("저장할 이름")
.setView(alert_layout2)
.setPositiveButton("LOAD", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
filename = alert_edit2.getText().toString();
save(filename);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainAc.this,"save 취소",Toast.LENGTH_SHORT).show();
}
}).show();
}else{
save(filename);
}
break;
case R.id.delete:
Log.i("TAG", "delete 진행");
if(filename == null){
Toast.makeText(MainAc.this, "삭제파일이 없습니다.", Toast.LENGTH_SHORT).show();
}else {
delete(filename);
filename = null;
}
break;
}
}
};
** AlertDialog를 추가하면서 load, save, delete 기능은 별도의 메소드로 뽑아두었습니다.
** AlertDialog를 추가하면서 이점은 새로운 파일을 불러와서 수정, 삭제할 수 있습니다.
그리고 save기능에서 처음 어플을 실행하면 null로 설정이 되어있기 때문에
처음 파일을 불러오지 않고 저장하는 경우 새로운 파일이름을 입력 받기 위해서 AlertDialog를 추가하였습니다.
(이후 파일을 불러온 이후로 새로운 파일을 생성할 수 없습니다. - 다음에 추가하도록 하겠습니다.)
** AlertDialog의 editText창을 추가하기 위해서 별도의 레이아웃 xml을 생성한 이후 inflate를 통해서 AlertDialog에 추가하였습니다.
**alert_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/search_memo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="메모 이름 입력"/>
</LinearLayout>
새로운 레이아웃은 edittext만 추가한 이후 inflate로 xml을 LinearLayout 객체로 생성한 이후에
AlertDialog의 setView메소드를 통해서 추가시켜주면 됩니다.
**load(), save(), delete() 메소드
public void load(String filename){
FileInputStream fis = null;
try{
fis = openFileInput(filename);
byte[] data = new byte[fis.available()];
while( fis.read(data) != -1){
}
inputText.setText(new String(data));
Toast.makeText(MainAc.this, "load 완료", Toast.LENGTH_SHORT).show();
}catch(Exception e){
e.printStackTrace();
}finally{
try{ if(fis != null) fis.close(); }catch(Exception e){e.printStackTrace();}
}
}
public void save(String filename){
FileOutputStream fos = null;
try{
fos = openFileOutput(filename, Context.MODE_PRIVATE);
String out = inputText.getText().toString();
fos.write(out.getBytes());
Toast.makeText(MainAc.this, "save 완료", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(MainAc.this, "저장할 파일명을 입력하세요", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}finally{
try{ if(fos != null) fos.close(); }catch(Exception e){e.printStackTrace();}
}
}
public void delete(String filename){
boolean b = deleteFile(filename);
if(b){
Toast.makeText(MainAc.this, "delete 완료", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainAc.this, "delete 실패", Toast.LENGTH_SHORT).show();
}
}
새로 만든 메소드는 이전과 비슷하지만 filename을 매개변수로 받아오는 차이점만 있습니다.
'Android' 카테고리의 다른 글
안드로이드 - 어플 초기화면 만들기 (0) | 2017.08.30 |
---|---|
안드로이드 - 초간단 메모장 만들기3(옵션 추가) (0) | 2017.08.29 |
안드로이드 - Thread (AsyncTask) (0) | 2017.08.26 |
android - webview(웹뷰)예제 (0) | 2017.08.26 |
android - 안드로이드 SQLite execSQL()과 rawQuery()의 차이 (0) | 2017.08.25 |