화면에 저장된 값 불러오기 ( key-value )
- 응용프로그램의 실정정보를 영구적으로 저장하는 장치(용량이 작다)
- 사용자의 옵션선택사항이나 프로그램 자체의 구성정보를 저장할때 주로 사용한다. (세팅파일 또는 ini파일과 유사한 기능 )
(1) activity_main.xml
; Edit두개
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
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" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="학생이름입력" />
<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="학생번호입력" />
<EditText
android:id="@+id/edtNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
</EditText>
</LinearLayout>
</LinearLayout>
(2) MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText edtName;
EditText edtNum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtName=(EditText)findViewById(R.id.edtName);
edtNum=(EditText)findViewById(R.id.edtNum);
SharedPreferences spf=getSharedPreferences("info",0);
//프레프런스에 저장된 값 얻어오기
//spf.getString("저장된키값",키가없을때 보여줄 정보)
String sname=spf.getString("sname","입력정보 없음");
String snum=spf.getString("snum","입력정보 없음");
//저장된 값들을 에디트텍스트에 넣기
edtName.setText(sname);
edtNum.setText(snum);
}
@Override
protected void onPause() {
super.onPause();
//프레프런스객체 얻어오기
//getSharedPreferences("파일명",모드):모드가 0이면 읽기쓰기 가능
SharedPreferences spf=getSharedPreferences("info",0);
//프레프런스에 정보를 기록하기 위한 에디트객체 얻어오기
SharedPreferences.Editor editor=spf.edit();
//에디트텍스트에 입력된 값 얻어오기
String sname=edtName.getText().toString();
String snum=edtNum.getText().toString();
//프레프런스에 넣기
editor.putString("sname",sname);
editor.putString("snum",snum);
//프레프런스에 저장하기
editor.commit();
}
}
- 이름과 번호를 입력한다. 에뮬레이터 우측의 버튼으로 화면 이동.
- info파일로 이름과 번호가 저장되었는지 확인.
이클립스에서 에뮬레이터를 탐색기로 볼수 있다.
DDMS 선택
- File Explorer 탭선택
- data / data / 밑에 해당 테스트 중인 프로젝트 선택
- info.xml
- 앞에 화살표 버튼으로 xml파일을 export한다.
- 열어보면
'Mobile > Android' 카테고리의 다른 글
#25 ( popup dialog ) (0) | 2013.02.03 |
---|---|
#24 ( File ) (0) | 2013.02.03 |
#22 ( Activity LifeCycle ) (0) | 2013.02.03 |
#21 ( Intent Action : 외부 프로그램과 연결 ) (0) | 2013.02.02 |
#20 ( 다른 Activity 로 text와 이미지 넘기기 ) (0) | 2013.02.02 |