• 검색 결과가 없습니다.

학습목표

N/A
N/A
Protected

Academic year: 2022

Share "학습목표"

Copied!
18
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

1 학습목표

❍ 내장 메모리의 파일을 처리하는 방법을 배운다.

❍ SD카드의 파일을 처리하는 방법을 배운다.

2 확인해 볼까?

지금까지 만든 앱은 종료하면 그동안 작업했던 내용은 모두 사라진다. 앱을 종 료했다가 다시 실행했을 때 사용한 곳부터 이어서 작업하려면 어떻게 해야 할까?

3 내장 메모리 파일 처리

1) 학습하기

앱을 종료했다가 다시 실행했을 때 사용한 곳부터 이어서 작업하려면 내장 메 모리에 파일을 저장하고 읽어오는 방법을 사용해야 한다. 내장 메모리의 저장 위 치는 “/data/data/패키지명/files” 폴더이다. 패키지명은 앱 마다 고유한 이름을 가지므로 앱 마다 서로 다른 저장소를 가진다고 생각하면 된다. 내장 메모리에서 파일 입출력의 일반적인 절차는 [그림 10-1]과 같다.

[그림 10-1] 내장 메모리를 사용한 파일 처리

(2)

[예제 10-1]main.xml 1

2 3 4 5

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

활동하기 실습을 통해 내장 메모리에서 간단히 파일을 쓰고 읽는 방법을 배우 도록 하자.

2) 활동하기 ❍ 활동 개요

간단한 사용자 정보를 입력받아 텍스트로 저장하는 기능과 텍스트에 저장된 사 용자의 정보를 출력해주는 앱을 만들어 보자.

❍ 활동 과정

(1) 새로운 안드로이드 프로젝트를 만들고 이름은 Memory로 한다. 프로젝트 생성 과 정은 2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따 른다.

(2) Package Explorer에서 [Memory]-[res]-[layout]-[main.xml] 파일을 열고, [main.xml]

탭을 클릭하여 화면을 구성한다. 화면 구성은 다음과 같다.

. RelativeLayout을 LinearLayout으로 변경하고 orientation을 vertical로 설정한다.

. 큰 LinearLayout 내부에 TextView, LinearLayout 2개, Button 2개, TextView 2개 로 구성한다.

. 2개의 내부 LinearLayout의 orientation을 horizontal로 설정하고 TextView와 EditText로 구성한다.

. 적절히 padding과 layout_margin을 설정한다.

. 결과를 보여주는 마지막 텍스트 뷰는 글자크기 20dp로 하고 배경생은 회색으로 글씨 색상은 빨강으로 설정한다.

(3)

6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

android:padding="10dp"

tools:context=".MemoryActivity" >

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:text="사용자 정보 입력" />

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="사용자 이름: " />

<EditText

android:id="@+id/edtName"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1" />

</LinearLayout>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="이메일: " />

<EditText

android:id="@+id/edtEmail"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1" />

</LinearLayout>

<Button

android:id="@+id/btnWrite"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="내장 메모리에 파일 쓰기" />

<Button

android:id="@+id/btnRead"

(4)

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="내장 메모리에서 파일 읽기" />

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="10dp"

android:gravity="center"

android:text="파일에서 읽어온 내용 출력" />

<TextView

android:id="@+id/tvText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#CCCCCC"

android:textColor="#FF0000"

android:textSize="20dp" />

</LinearLayout>

[예제 10-2]MemoryActivity.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

package com.example.memory;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MemoryActivity extends Activity {

(3) 이클립스의 Package Explorer에서 [Memory]-[src]-[com.example.memory]- [MemoryActivity.java] 파일을 연다. onCreateOptionsMenu() 메소드는 사용하지 않으 므로 관련 부분을 삭제한다.

(5)

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

EditText edtName, edtEmail;

Button btnWrite, btnRead;

TextView tvText;

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.main);

setTitle("간단 파일 처리");

edtName = (EditText) findViewById(R.id.edtName);

edtEmail = (EditText) findViewById(R.id.edtEmail);

btnWrite = (Button) findViewById(R.id.btnWrite);

btnRead = (Button) findViewById(R.id.btnRead);

tvText = (TextView) findViewById(R.id.tvText);

btnWrite.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub try {

FileOutputStream outFs = openFileOutput("memory.txt",

Context.MODE_WORLD_WRITEABLE);

String str = "사용자 이름: " + edtName.getText().toString() + "\n이메일: " + edtEmail.getText().toString();

outFs.write(str.getBytes());

outFs.close();

Toast.makeText(getApplicationContext(),

"사용자 정보가 memory.txt에 저장되었습니다.", 0).show();

} catch (IOException e) { }

} });

btnRead.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

(6)

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

// TODO Auto-generated method stub try {

FileInputStream inFs = openFileInput("memory.txt");

byte[] txt = new byte[50];

inFs.read(txt);

String str = new String(txt);

tvText.setText(str);

inFs.close();

} catch (IOException e) {

Toast.makeText(getApplicationContext(), "파일이 없습니다", 0).show();

} } });

} }

39~50행 내장 메모리에 파일 쓰기를 try-catch 문으로 구현한다.

40~41행 memory.txt에 쓰기모드로 파일을 연다.

42~43행 파일에 쓰려는 사용자 정보를 문자열로 만든다.

44행 문자열을 파일에 쓴다. 이때 문자열을 getBytes() 메소드를 이용해 byte[]형으로 변경해 야 한다.

45행 파일을 닫는다.

46~47행 파일이 저장되었다는 것을 토스트로 알려준다.

58~67행 내장 메모리로부터 파일 읽어오기를 try-catch 문으로 구현한다.

59행 내장 메모리의 /data/data/패키지명/files/memory.txt 파일을 읽어온다.

60~62행 byte[] 형 변수로 파일로부터 데이터를 읽어와서, 문자열로 변경한다.

63행 텍스트뷰에 읽어온 문자열을 출력한다.

64행 파일을 닫는다.

66행 읽어오려는 파일이 없으면 토스트를 띄운다.

(4) 프로젝트를 실행하여 결과를 확인한다. 에디트 텍스트에 사용자 이름과 이메일을 입력하고 <내장 메모리에 저장하기> 버튼을 클릭하면 "memory.txt" 파일에 저장했다 는 토스트가 출력될 것이다. 그 후에 <내장 메모리에서 읽어오기> 버튼을 클릭하면 파 일에 저장한 사용자 정보가 텍스트 뷰에 보일 것이다.

(7)

[그림 10-2] 내장 메모리 파일 처리 실행 결과

[그림 10-3] DDMS 실행

[그림 10-4] 파일 확인 1

(8)

[그림 10-5] 파일 확인 2

(5) AVD에서 동작하는 결과를 확인하였으면, “memory.txt” 파일을 직접 확인해보자.

이클립스에서 제공하는 DDMS 툴을 사용한다. 이클립스의 [Window]-[Open Perspective]를 선택한다. 만일 [DDMS]가 없다면 [Other]를 선택한다. [Open Perspective] 창이 나오면 [DDMS]를 선택하고 <OK>를 클릭하여 DDMS를 실행한다.

만일 [그림 10-3]과 같이 이클립스 화면의 오른쪽 위에 [DDMS] 아이콘이 보인다면 아 이콘을 클릭하여 DDMS를 실행하자.

(6) DDMS 화면 위의 [File Explorer] 탭을 선택하고, 화면 왼쪽의 Devices에서 현재 AVD인 [Google-4.1.2 [emulator-5556] ]을 클릭하면 가상장치의 폴더와 파일 목록이 보 인다. [그림 10-4]와 같이 [data]-[data] 폴더로 들어간다.

(7) 많은 패키지 중에서 [com.example.memory]-[files] 폴더로 들어가면, [그림 10-5]와 같이 생성한 “memory.txt” 파일이 보인다.

(8) 파일을 PC로 가져올 수도 있다. PC로 가져올 파일을 선택하고 오른쪽 위의 [Pull a file from the device] 아이콘을 클릭한 후 저장할 PC의 폴더를 선택하면 된다.

(9)

[그림 10-6] PC에 파일 저장

(9) 다시 안드로이드 개발 환경으로 돌아오고 싶다면 이클립스 화면 오른쪽 위의 [Java perspective] 아이콘을 클릭하면 된다.

4 SD카드 파일 처리

1) 학습하기

안드로이드에서 응용 프로그램들이 공용으로 사용할 음악 파일, 영상 파일, 그 림 파일 등과 같은 미디어 파일은 SD카드에 저장하여 활용한다. SD카드를 활용 하여 미디어 파일을 관리한다면 제한된 내장 메모리에 비해 훨씬 큰 공간을 사용 할 수 있으며 확장성도 뛰어나다. AVD도 가상의 SD카드를 장착할 수 있는데, 1 장에서 AVD를 생성할 때 128MB의 가상 SD카드를 설정하였다.

이클립스 메뉴 [Window]-[Android Virtual Device Manager]를 실행한 후 AVD Name에서 [Google-4.1.2]를 선택하고 <Edit> 버튼을 클릭하면 [그림 10-7]

과 같이 AVD에 장착한 SD카드를 확인할 수 있다. 만약 가상의 SD카드 메모리 Size가 설정되어 있지 않다면 적당한 크기 (256M 이내)를 입력한다.

(10)

[그림 10-7] AVD의 가상 SD카드 확인

2) 활동하기 ❍ 활동 개요

SD카드에서 파일을 읽어오는 간단한 앱을 구현해보자. SD카드를 활용한 파일 처리는 mnt/sdcard/ 폴더를 사용하는 것 빼고는 내장 메모리의 경우와 유사하 다.

❍ 활동 과정

(1) 새로운 안드로이드 프로젝트를 만들고 이름은 SDCard로 한다. 프로젝트 생성 과 정은 2차시 ‘활동 과정: 안드로이드 응용 프로그램 작성해보기’의 (3)~(6)의 과정을 따 른다.

(2) Package Explorer에서 [SDCard]-[res]-[layout]-[main.xml] 파일을 열고, [main.xml]

탭을 클릭하여 화면을 구성한다. 화면 구성은 다음과 같다.

. RelativeLayout을 LinearLayout으로 변경하고 orientation을 vertical로 설정한다.

. 큰 LinearLayout 내부에 TextView, LinearLayout 2개, Button 2개, TextView 2개

(11)

[예제 10-3]main.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".SDCardActivity" >

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:text="학생 정보 입력" />

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="학번: " />

<EditText

android:id="@+id/edtStNum"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1" />

</LinearLayout>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content" >

<TextView

android:layout_width="wrap_content"

로 구성한다.

. 2개의 내부 LinearLayoutd의 orientation을 horizontal로 설정하고 TextView와 EditText로 각각 구성한다.

. 적절히 padding과 layout_margin을 설정한다.

. 결과를 보여주는 마지막 텍스트 뷰는 글자크기 20dp로 하고 배경생은 회색으로 글씨 색상은 빨강으로 한다.

(12)

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

android:layout_height="wrap_content"

android:text="이름 " />

<EditText

android:id="@+id/edtName"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1" />

</LinearLayout>

<Button

android:id="@+id/btnWrite"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="SD카드에 파일 쓰기" />

<Button

android:id="@+id/btnRead"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="SD카드에서 파일 읽기" />

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="10dp"

android:gravity="center"

android:text="파일에서 읽어온 내용 출력" />

<TextView

android:id="@+id/tvText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="#CCCCCC"

android:textColor="#FF0000"

android:textSize="20dp" />

</LinearLayout>

(3) 이클립스의 Package Explorer에서 [SDCard]-[src]-[com.example.sdcard]- [SDCardActivity.java] 파일을 연다. onCreateOptionsMenu() 메소드는 사용하지 않으므 로 관련 부분을 삭제한다.

(13)

[예제 10-4]SDCardActivity.xml 1

2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

package com.example.sdcard;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class SDCardActivity extends Activity {

EditText edtName, edtStNum;

Button btnWrite, btnRead;

TextView tvText;

String SDPath;

@Override

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

setContentView(R.layout.main);

edtName = (EditText) findViewById(R.id.edtName);

edtStNum = (EditText) findViewById(R.id.edtStNum);

btnWrite = (Button) findViewById(R.id.btnWrite);

btnRead = (Button) findViewById(R.id.btnRead);

tvText = (TextView) findViewById(R.id.tvText);

SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();

btnWrite.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

(14)

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

File dir = new File(SDPath + "/dir");

dir.mkdir();

File file = new File(SDPath + "/sdcard.txt");

try {

FileOutputStream outFs = new FileOutputStream(file);

String str = "학번: " + edtStNum.getText().toString()

+ "\n이름: " + edtName.getText().toString();

outFs.write(str.getBytes());

outFs.close();

Toast.makeText(getApplicationContext(),

"학생 정보가 sdcard.txt에 저장되었습니다.", 0).show();

} catch (IOException e) { }

} });

btnRead.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub try {

FileInputStream inFs = new FileInputStream(SDPath + "/dir/sdcard.txt");

byte[] txt = new byte[50];

inFs.read(txt);

String str = new String(txt);

tvText.setText(str);

inFs.close();

} catch (IOException e) {

Toast.makeText(getApplicationContext(), "파일이 없습니다", 0).show();

} } });

} }

33행 SD카드의 절대경로를 얻어와서 SDPath에 대입한다.

40~41행 SD카드에 [dir] 폴더를 생성한다.

42, 44행 [mnt]-[sdcard]-[dir] 폴더에 "sdcard.txt" 파일을 생성하고 쓰기위해 연다.

62행 [mnt]-[sdcard]-[dir] 폴더에 "sdcard.txt" 파일을 읽기위해 파일을 연다.

(15)

(4) 프로젝트를 실행하여 결과를 확인한다. 에디트 텍스트에 학번과 이름을 입력하고

<SD카드에 파일 쓰기> 버튼을 클릭하면 토스트 메시지가 보이지 않을 것이다. 매니페 스트 파일에 SD카드에 쓰기 권한에 대한 퍼미션을 설정해주도록 하자.

[그림 10-8] SDCard 파일 쓰기권한 퍼미션 설정

(5) 매니페스트 파일을 열고 아래의 [Permission] 탭을 선택한 후 <Add> 버튼을 클릭 한다. 창이 나오면 [Uses Permission]을 선택한 후 <OK> 버튼을 클릭한다. [그림 10-8]

과 같이 오른쪽에 [Attributes for Users Permission]이 나오면, Name 필드 오른쪽 끝 에 콤보박스 화살표를 눌러 [android.permission.WRITE_EXTERNAL_S TORAGE]를 선 택한다. 저장한 후 아래의 [AndroidManifest.xml] 탭을 눌러보자. <uses-permission android:name="android.permission. WRITE_EXTERNAL_STORA GE"/> 내용이 추가 된 것을 확인할 수 있을 것이다.

(6) 프로젝트를 실행하여 결과를 확인한다. 에디트 텍스트에 학번과 이름을 입력하고

<SD카드에 파일 쓰기> 버튼을 클릭하면 "학생 정보가 sdcard.txt에 저장되었습니다"

는 토스트가 출력될 것이다. 그 후에 <SD카드에서 파일 읽> 버튼을 클릭하면 파일에 저장한 학생 정보가 텍스트 뷰에 보일 것이다.

(16)

[그림 10-9] SDCard 파일 처리 실행 결과

(7) AVD에서 동작하는 결과를 확인하였으면, 사용자 정보가 쓰여진 파일을 직접 확 인해보자. 이클립스 화면 우즉상단의 [DDMS] 아이콘을 클릭한 후 [File Explorer]에서 [mnt]-[sdcard]-[dir] 폴더에 검색해보면 [그림 10-10]와 같이 “sdcard.txt” 파일이 저장되 어 있음을 확인할 수 있을 것이다.

[그림 10-10] [mnt]-[sdcard] 폴더에 [dir]폴더와 sdcard.txt 파일 생성

(17)

5 배운 내용 정리

1) 내장 메모리의 파일 처리하는 방법은 다음과 같다.

2) SDCard의 파일 처리하는 방법은 파일 저장 위치만 다를 뿐 내장 메모리의 경우와 유사하다. 다만, SDCard에 파일을 저장하고자 하는 경우에는 반드시 퍼미션이 필요하 다.

6 학습 확인하기

1) 내장 메모리의 파일을 저장하는 위치가 어디인지 설명하라.

2) SDCard의 파일을 저장하는 위치가 어디인지 설명하라.

3) SDCard에 파일을 저장하기 위해 필요한 퍼미션이 무엇인지 설명하라.

7 지식창고

❍ 참고문헌

[1] 우재남, 이복기, “안드로이드 프로그래밍”, 한빛미디어, 2012 [2] 김상형, “안드로이드 프로그래밍 정복”, 한빛미디어, 2011

❍ 참고사이트

[1]

http://developer.android.com/

(18)

[2]

http://developer.android.com/reference

참조

관련 문서

실업률은 경제상황과 경제정책의 성공여부를

[r]

[r]

지역워크넷 고용복지 센터 + 장애인고용포털 로그인 회원가입 챗봇(시범) 이용안내 고객센터 원격지원 사이트맵 글자크기.

② 고구려어와 퉁구스어와의 관계 &gt; 신라어와 퉁구스어와의 관계 (고구려어는 퉁구스와 신라어 중간 정도 위치)... 학교문법에서는 이 견해를

 표본의 특성을 요약하여

갂다라는 16대 부족국가(Maha-Jana-pada) 시대에 아프가니스탄과 파키스탄 일대에 번성했던 국가로, B.C.6세기 다리우스 1세가 제국을 건설하면서 페르시아의 영향

띄어쓰기를 포함하고 있으며, 부록으로 문장부호 규정도 있음. 국어의 로마자 표기 원칙.. 따라서 된소리로 발음되는 것은 된소리로 적는다.. 표기법은 보수성을 지닌