Android 프로그래밍 2

본문 바로가기
사이트 내 전체검색


Android 프로그래밍 2
Android 프로그래밍 2

1. SharedPreferences 실습

페이지 정보

작성자 관리자 댓글 0건 조회 1,279회 작성일 21-06-11 10:15

본문

1. SharedPreferences 실습

안드로이드는 간단한 데이터의 저장을 목적으로 SharedPreferences를 제공한다.

SharedPreferences는 내부저장소를 이용하기 때문에 권한 설정이 필요 없고 훨씬 간단한 코드로 사용할 수 있다.

주로 로그인 정보나 앱의 상태 정보를저장하는 용도로 사용된다.


SharedPreferences는 인텐트에 값을 전달하듯이 데이터를 키와 값 쌍으로 저장할 수 있다. 

데이터는 XML형식으로 된 파일로 저장되며 앱이 종료되어도 남아 있다.


값을 저장할 때는 4단계를 거쳐 저장한다.

- 1단계 : SharedPreference 생성한다.

- 2단계 : Editor를 꺼낸다.

- 3단계 : putInt(), putString()메소드로 저장한다.

- 4단계 : apply()로 파일에 반영한다.


2단계에 걸쳐 값을 불러온다.

-1단계 : SharedPreference 생성한다

- 2단계 : getInt(), getString()메소드로 값을 읽어온다.


값을 읽어올때는 apply()가 필요하지 않다.


1. 프로젝트 생성 

프로젝트명 : SharedPreferencesTest



2. SecondActivity 생성



1.PNG



2. Main 레이아웃에 버튼 추가

파일명 : activity_main.xml


<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout 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"

    tools:context=".MainActivity">


    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Second"

android:id="@+id/button1" 

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>



3. MainActivity에서 데이터 저장하기

파일명 : MainActivity.kt


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        // 1단계 : SharedPreference 생성하기

        val shared = getSharedPreferences("이름", Context.MODE_PRIVATE)

        //2단계 : editor 꺼내기

        val editor = shared.edit()

        //3단계 : 값저장하기

        //editor.putString("키", "값")

        editor.putString("name", "leejinkwan")

        //4단계 : 파일에 반영하기

        editor.apply()


        // SecondActivity 실행

        val button1 = findViewById<Button>(R.id.button1)

        button1.setOnClickListener {

            val second = Intent(this, SecondActivity::class.java)

            startActivity(second)

        }


    }

}


getSharedPreferences()는 Context를 가지고 있는 모든 컴포넌튼에서 접근과 호출이 가능하다.

첫번째 파라메터는 입력된 데이터가 저장될 파일명을, 두번째 파라미터에는 파일 접근 권한을 설정한다.

보안상의 이유로 MODE_PRIVATE만 사용한다.


getPreferences()는 개별 액티비티에서 사용하거나 액티비티가 하나밖에 없는 앱에서 사용할 수 있다.

호출하는 액티비티이름으로 저장 파일이 생성된다.



4. Second 레이아웃 수정

파일명 : activity_second.xml 


<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout 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"

    tools:context=".SecondActivity">


    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/myname"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent"  />

    

</androidx.constraintlayout.widget.ConstraintLayout>



5. SecondActivity 수정

파일명 : SecondActivity.kt


class SecondActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_second)

        

        // 1단계 : SharedPreference 생성하기

        val shared = getSharedPreferences("이름", Context.MODE_PRIVATE)

        //2단계 : 값가져오기

        //shared.getString("키","기본값")

        val myname1 = shared.getString("name","")


        // TextView에 값 출력

        val tv_myname = findViewById<TextView>(R.id.myname)

        tv_myname.text = myname1

    }

}



6. 실행


댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.