아이디, 패스워드를 이용해서 접속하는 앱, 사이트들을 보면
아이디, 패스워드를 저장해놓고 다음에 접속하기 편하게 하는 기능들이 있다.
이런 간단한 데이터를 저장하는 기능을 알아봅시다.
아이디, 패스워드를 입력하는 화면을 만들어 보자.
1. 메인화면(activity_main.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">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="아이디"/>
<EditText
android:id="@+id/idText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="아이디"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:text="아이디"/>
<EditText
android:id="@+id/pwText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:inputType="numberPassword"
android:hint="비밀번호"/>
</LinearLayout>
</LinearLayout>
실제 실행화면
2. 코드화면(MainActivity.java)
EditText idText;
EditText pwText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
idText = findViewById(R.id.idText);
pwText = findViewById(R.id.pwText);
}
//액티비티가 사용자에게 보이지 않을때 실행
@Override
protected void onStop() {
super.onStop();
saveState();
}
// 액티비티가 화면에 보여지기 전에 실행
@Override
protected void onResume() {
super.onResume();
restoreState();
}
protected void saveState(){
SharedPreferences pref = this.getSharedPreferences("pref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String id = idText.getText().toString();
String pw = pwText.getText().toString();
editor.putString("id", id);
editor.putString("pw", pw);
editor.commit();
}
protected void restoreState(){
SharedPreferences pref = this.getSharedPreferences("pref", Activity.MODE_PRIVATE);
if(pref != null){
String id = "";
String pw = "";
id = pref.getString("id","");
pw = pref.getString("pw","");
idText.setText(id);
pwText.setText(pw);
}
}
1. xml에서 만들어 놓은 EditText 객체를 생성
2. saveState 메소드는 sharedPreferences 객체 생성 후
id와 pw를 putString을 통해 저장한다.
3. restoreState 메소드는 저장해 놓은 id와 pw를
getString를 통해 얻어와 EditText에 넣어준다.
[안드로이드] 세 번째 안드로이드 앱 개발[전국도서관정보앱] (0) | 2020.04.21 |
---|---|
[안드로이드] GPS 상태확인 (0) | 2020.04.20 |
[안드로이드] 스피너(spinner) 드롭다운 사용방법 (2) | 2020.04.18 |
[안드로이드] 드로어블 이미지 클릭 상태 변경 (0) | 2020.04.17 |
[안드로이드] 엑셀(xls) 파일 등록, 읽기 (6) | 2020.04.16 |
댓글 영역