shared preference는 환경설정 같은 거 저장하는 곳이다.
package com.example.a0408;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int[] layoutIds = {R.id.layoutForm, R.id.layoutHome}; // layout findviewbyid 할 때 거기 넣을 id를 배열로 만든 것.
private LinearLayout[] layouts; // 레이아웃 객체 만들어서 배열로 만들어서 초기화 해 줄 예정
private EditText editTextUserName; // editText 로그인 할 때 editText 객체 가져오는 것.
private TextView textViewUserName; // textViewUserName 텍스트 뷰 로그인 됐을 때 띄울 곳.
private SharedPreferences preferences; // sharedpreference? key: value 형태의 간단한 데이터가 저장된다.
// 쿠키같은 객체라고 볼 수 있다. 액티비티 종료 이후에도 데이터 저장가능.. key값이 있어서 따로 저장한다.
// getString 이런걸로 저장된 값을 가져올 수 있다.
// shared preference 는 사용할 때 getEditor() 함수를 써서 Editor 객체를 따로 저장하고,
// 변화 내용은 apply나 commit으로 저장하는데, 왠만하면 apply 써라. 비동기 방식이라서 입출력 도중에 멈추지 않으니까.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i =0;i<layoutIds.length;i++){
layouts[i] = findViewById(layoutIds[i]);
}
// layouts << 리니어레이아웃 배열 거기 안에 아까 저장해놓은 아이디 등록하면 됨.
editTextUserName = findViewById(R.id.editTextUserName);
textViewUserName = findViewById(R.id.textViewUserName);
preferences = getSharedPreferences("user", MODE_PRIVATE);
// 아까 말한 쿠키 같은 거.
// preferece는 get~으로 가져온 걸 저장. 파일로 실제로 저장이 되며,
// name은 해당 preferences의 이름이다. 해당 이름으로 생성할 수 있다는 것은 xml 파일이 그 이름으로 생성된다는 뜻
// mode는 읽고 쓰기에 관련된 mode
// 읽는거는 sharedpreference 객체 에서 getInt << int 형 getString << string 형 파라메터 : key, default 값
// 쓰는거는 sharedpreference 객체로 edit(); 만들어서 editor.putString() key, value 형태로 저장.
// commit이나 apply로 저장
// onCreate 함수 얻은 뒤에 로그인 상태 확인해서 바로 화면 제공하는 방법
// 로그인 정보는 어디에 담겨있지? userName이 preference의 userName에 있음.
String userName = preferences.getString("userName", null);
if(userName.length() != 0){
textViewUserName.setText(userName);
showLayout(R.id.layoutForm);
}else showLayout(R.id.layoutHome);
}
private void showLayout(int id){ // showLayout은 리니어 레이아웃 검사해서 이 아이디는 보여주고, 다른 아이디는 gone 처리 해줘.
for(LinearLayout layout: layouts){
if(id == layout.getId())
layout.setVisibility(View.VISIBLE);
else
layout.setVisibility(View.GONE);
}
}
public void onLogin(View v){ // 1. null 검사하기.. edittext꺼 가져오고, 2. editor가져와서 저장 3. textView에 담자.
if(preferences == null) return;
String userName = editTextUserName.getText().toString().trim(); // text가져와서 string으로 한다음에 공백제거
if(userName.length() == 0) return; // nullpointexception
SharedPreferences.Editor editor = preferences.edit();
editor.putString("userName", userName);
editor.apply();
// editor로 저장
textViewUserName.setText(userName);
showLayout(R.id.layoutHome); // layout바꿔주는 메소드 사용하기 바꿔주자~
}
public void onLogout(View v){
if(preferences == null) return; // null point exception 방지 //
SharedPreferences.Editor editor = preferences.edit();
editor.remove("userName"); // userName 항목 하나만 지우고 싶으니까.
editor.apply();
textViewUserName.setText(null);
showLayout(R.id.layoutForm);
}
}
'2학년 > 안드로이드' 카테고리의 다른 글
0415 android (0) | 2019.04.15 |
---|---|
0412 (0) | 2019.04.12 |
0408 android (0) | 2019.04.08 |
0404 android (0) | 2019.04.04 |
0401 android_SQLite on android (0) | 2019.04.01 |