기본적으로 Android의 시작인 API 레벨 1부터 Android에서 Key 값 쌍을 저장하는 API를 사용할 수 있게 되었습니다. 이 API는 Android를 처음 사용하거나 sharedpreferences를 사용하는 방법을 배우고 있는 경우입니다.

이 튜토리얼에서는 sharedpreferences를 사용하여 데이터를 저장하고 검색하는 방법에 대한 몇 가지 예를 살펴보겠습니다. 대부분 기본 dtaa 유형을 sharedpreferences에 저장할 것입니다.

예제 1: Kotlin Android - SharedPreferences 예제

이것은 Kotlin으로 작성된 간단한 sharedpreferences 예제입니다.

데모

다음은 생성된 데모입니다.

Kotlin Android 공유 환경 설정 예

1단계: 종속성

특별한 종속성 또는 타사 종속성이 필요하지 않습니다.

2단계: 레이아웃 디자인

다음과 같이 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"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:textColor="#101010"
        android:textSize="25sp"/>

    <EditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_a_text"
        android:layout_margin="10dp"
        android:textColor="#101010"/>

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/save"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show"
        android:layout_margin="10dp"/>

</LinearLayout>

3단계: 코드 작성

그런 다음 다음과 같이 kotlin 코드를 작성합니다.

MainActivity.kt

다음은 주요 활동에 대한 전체 코드입니다.

package arb.test.shared.perferences

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    lateinit var shared : SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        shared = getSharedPreferences("Test" , Context.MODE_PRIVATE)

        save.setOnClickListener {

            val edit = shared.edit()
            edit.putString("txt" , edt.text.toString())
            Toast.makeText(this , "Was Saved" , Toast.LENGTH_SHORT).show()
            edit.apply()
        }

        show.setOnClickListener {

            txt.text = shared.getString("txt" , "No imported" )
            Toast.makeText(this ,  shared.getString("txt" , "No imported" ) , Toast.LENGTH_SHORT).show()
        }

    }
}

운영

프로젝트 실행

참조

다운로드 링크는 다음과 같습니다.

다운로드 코드
찾아보기 코드

예제 2: SharedPreferences를 사용한 세션 관리

이 예에서는 예를 들어 사용자가 SharedPreferences를 사용하여 앱에 로그인한 후 사용자 세션을 관리하는 방법을 배웁니다. 이 예제는 Kotlin으로도 작성되었습니다.

다음 세 가지 파일이 포함되어 있습니다.

  1. 두 가지 활동 - 첫 번째 활동과 로그인 활동.
  2. 세션 관리자 - SharedPreferences 클래스

시작하자.

1단계: 프로젝트 생성

빈 'Android Studio' 프로젝트를 생성하여 시작합니다.

2단계: 종속성

이 프로젝트에는 외부 종속성이 필요하지 않습니다.

3단계: 레이아웃을 디자인합니다.

우리는 두 가지 레이아웃을 디자인할 것입니다:

(ㅏ). 활동_login.xml

로그인 활동입니다. 두 개의 TextView와 버튼을 추가합니다.

<?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"
    android:gravity="center"
    tools:context=".LoginActivity">

    <TextView
        android:id="@+id/Disp_Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Username"
        android:textColor="@color/colorPrimary"/>

    <TextView
        android:id="@+id/Disp_Password"
        android:layout_marginTop="20dp"
        android:textColor="@color/colorPrimary"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"/>

    <Button
        android:id="@+id/btnLogout"
        android:layout_marginTop="40dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:text="Logout"/>

</LinearLayout>

(비). 활동_first.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:gravity="center"
    android:orientation="vertical"
    tools:context=".FirstActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Session Management"
        android:textColor="@color/colorPrimary"
        android:textSize="30sp"/>

    <EditText
        android:id="@+id/txtUsername"
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:textColorHint="@color/colorPrimary"
        android:textColor="@color/colorPrimary"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@null"
        android:hint="Username"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"/>

    <EditText
        android:id="@+id/txtPassword"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:textColorHint="@color/colorPrimary"
        android:textColor="@color/colorPrimary"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@null"
        android:hint="Password"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:background="@color/colorPrimary"/>

    <Button
        android:id="@+id/btnLogin"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:text="Login"
        android:textColor="@android:color/white"
        android:background="@color/colorPrimary"/>

</LinearLayout>

4단계: 세션 관리자 생성

sharedpreferences를 사용하여 세션 관리자를 만듭니다. SharedPreferences 객체, SharedPreferences.Editor 객체, Context 객체 및 개인 모드를 나타내는 정수 인스턴스 필드와 함께 SessionManager.kt 파일을 생성하여 시작합니다.

class SessionManager {

    var pref: SharedPreferences
    var edior: SharedPreferences.Editor
    var context: Context
    var PRIVATE_MODE: Int = 0

생성자에서 초기화합니다.

    constructor(context: Context) {

        this.context = context
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        edior = pref.edit()
    }

컴패니언 개체에서 정적 필드를 정의합니다.

    companion object {

        val PREF_NAME: String = "KotlinDemo"
        val IS_LOGIN: String = "isLogin"
        val KEY_NAME: String = "name"
        val KEY_PASS: String = "pass"

    }

로그인 세션을 만드는 방법은 다음과 같습니다.

    fun createLoginSession(name: String, emai: String) {

        edior.putBoolean(IS_LOGIN, true)
        edior.putString(KEY_NAME, name)
        edior.putString(KEY_PASS, emai)
        edior.commit()
    }

로그인을 확인하는 방법은 다음과 같습니다.

    fun checkLogin() {

        if (!this.isLoggedIn()) {
            var i: Intent = Intent(context, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(i)
        }
    }

다음은 sharedpreferences에서 사용자 세부 정보를 가져와 HashMap에 반환하는 방법입니다.

    fun getUserDetails(): HashMap<String, String> {

        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
        (user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())

        return user
    }

사용자를 로그아웃하는 방법은 다음과 같습니다.

    fun LogoutUser() {
        edior.clear()
        edior.commit()

        val i: Intent = Intent(context, LoginActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        context.startActivity(i)
    }

사용자가 로그인했는지 확인하는 방법은 다음과 같습니다.


    fun isLoggedIn(): Boolean {

        return pref.getBoolean(IS_LOGIN, false)
    }

전체 코드는 다음과 같습니다.

세션매니저.kt

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import com.example.sessionmanagementusingkotlin.FirstActivity
import com.example.sessionmanagementusingkotlin.LoginActivity

class SessionManager {

    var pref: SharedPreferences
    var edior: SharedPreferences.Editor
    var context: Context
    var PRIVATE_MODE: Int = 0

    constructor(context: Context) {

        this.context = context
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        edior = pref.edit()
    }

    companion object {

        val PREF_NAME: String = "KotlinDemo"
        val IS_LOGIN: String = "isLogin"
        val KEY_NAME: String = "name"
        val KEY_PASS: String = "pass"

    }

    fun createLoginSession(name: String, emai: String) {

        edior.putBoolean(IS_LOGIN, true)
        edior.putString(KEY_NAME, name)
        edior.putString(KEY_PASS, emai)
        edior.commit()
    }

    fun checkLogin() {

        if (!this.isLoggedIn()) {
            var i: Intent = Intent(context, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            context.startActivity(i)
        }
    }

    fun getUserDetails(): HashMap<String, String> {

        var user: Map<String, String> = HashMap<String, String>()
        (user as HashMap).put(KEY_NAME, pref.getString(KEY_NAME, null).toString())
        (user as HashMap).put(KEY_PASS, pref.getString(KEY_PASS, null).toString())

        return user
    }

    fun LogoutUser() {
        edior.clear()
        edior.commit()

        val i: Intent = Intent(context, LoginActivity::class.java)
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
        context.startActivity(i)
    }

    fun isLoggedIn(): Boolean {

        return pref.getBoolean(IS_LOGIN, false)
    }

}

5단계: 활동 만들기

두 가지 활동이 있습니다.

(ㅏ). FirstActivity.kt

사용자를 로그인하고 SharedPreferences에 세부 정보를 저장합니다.

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.sdnkcreations.sessionmanagerinkotlin.SessionManager
import kotlinx.android.synthetic.main.activity_first.*

class FirstActivity : AppCompatActivity() {

    lateinit var session: SessionManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_first)

        session = SessionManager(applicationContext)
        if (session.isLoggedIn()) {
            var i: Intent = Intent(applicationContext, FirstActivity::class.java)
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(i)
            finish()
        }

        btnLogin.setOnClickListener {

            val username: String = txtUsername.text.toString()
            val password: String = txtPassword.text.toString()

            if (username.trim().length > 0 && password.trim().length > 0) {

                session.createLoginSession(username, password)
                var i: Intent = Intent(applicationContext, LoginActivity::class.java)
                startActivity(i)
                finish()

            } else {

                Toast.makeText(this, "Login Failed...\n Please enter both credential", Toast.LENGTH_LONG).show()
            }

        }
    }
}

(비). 로그인 활동.kt

로그인한 사용자의 세부 정보를 표시합니다.

class LoginActivity : AppCompatActivity() {

    lateinit var session: SessionManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        session = SessionManager(applicationContext)
        session.checkLogin()

        val user: HashMap<String, String> = session.getUserDetails()

        val name: String = user.get(SessionManager.KEY_NAME)!!
        val pass: String = user.get(SessionManager.KEY_PASS)!!

        Disp_Username.setText("Name: " + name)
        Disp_Password.setText("Email: " + pass)
        btnLogout.setOnClickListener {

            session.LogoutUser()
        }
    }
}

운영

코드를 복사하거나 아래 링크에서 다운로드하여 빌드하고 실행합니다.

참조

참조 링크는 다음과 같습니다.

다운로드 예제

SharedPreferences 스니펫

이 튜토리얼에서는 SharedPreferences가 무엇인지, 왜 중요한지, 몇 가지 예를 살펴보고자 합니다.

다음은 SharedPreferences의 몇 가지 예입니다.

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.MainThread;

import com.jiangkang.tools.King;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.Set;

public class SpUtils {

    private SharedPreferences preferences;
    private static final String DEFAULT_PREF_NAME = "ktools_pref";
    private SharedPreferences.Editor editor;

    public static SpUtils getInstance(Context context,String name){
        return new SpUtils(context,name);
    }

    private SpUtils(Context context, String name) {
        preferences = context.getSharedPreferences(name,Context.MODE_PRIVATE);
        editor = preferences.edit();
    }

    public <T> SpUtils put(String key, T value){
        if (value instanceof String){
            editor.putString(key, (String) value);
        }else if (value instanceof Boolean){
            editor.putBoolean(key, (Boolean) value);
        }else if (value instanceof Integer){
            editor.putInt(key, (Integer) value);
        }else if (value instanceof Long){
            editor.putLong(key, (Long) value);
        }else if (value instanceof Float){
            editor.putFloat(key, (Float) value);
        }else {
            throw new IllegalArgumentException("value can not support");
        }
        return this;
    }

    public SpUtils putString(String key, String value){
        editor.putString(key,value).commit();
        return this;
    }

    public SpUtils putBoolean(String key, boolean value){
        editor.putBoolean(key, value).commit();
        return this;
    }

    public SpUtils putInt(String key, int value){
        editor.putInt(key,value).commit();
        return this;
    }

    public SpUtils putFloat(String key, float value){
        editor.putFloat(key, value).commit();
        return this;
    }

    public SpUtils putLong(String key, long value){
        editor.putLong(key, value).commit();
        return this;
    }

    public SpUtils putJsonObject(String key, JSONObject object){
        editor.putString(key,object.toString());
        return this;
    }

    public JSONObject getJsonObject(String key){
        String jsonString = preferences.getString(key,"{}");
        try {
            return new JSONObject(jsonString);
        } catch (JSONException e) {
            return null;
        }
    }

    public String getString(String key,String defaultValue){
        return preferences.getString(key,defaultValue);
    }

    public boolean getBoolean(String key, boolean defaultValue){
        return preferences.getBoolean(key, defaultValue);
    }

    public int getInt(String key, int defaultValue){
        return preferences.getInt(key, defaultValue);
    }

    public long getLong(String key, long defaultValue){
        return preferences.getLong(key, defaultValue);
    }

    public float getFloat(String key,float defaultValue){
        return preferences.getFloat(key, defaultValue);
    }

    public Map<String,?> getAll(){
        return preferences.getAll();
    }

}
2. SharedPreference에서 JSON 데이터를 저장하고 검색하는 방법

기본 응용 프로그램을 만드는 것으로 시작하겠습니다.

이 클래스는 Application 클래스에서 파생됩니다. 우리를 위해 할 일은 보류하고 애플리케이션 컨텍스트에 제공하는 것뿐입니다.

import android.app.Application;
import android.content.Context;

public class MainApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

그런 다음 애플리케이션 클래스를 만들었으므로 이제 json 데이터를 저장하고 로드할 수 있습니다.

첫 번째 방법은 'save()' 방법입니다. 두 개의 문자열과 Object를 수신합니다.

Google Gson 라이브러리를 사용하고 있습니다. 타사 라이브러리이므로 앱 수준 'build.gradle' 파일에 종속성으로 추가해야 합니다.

따라서 build.gradle 파일(앱 폴더에 있음)으로 이동하여 종속성 클로저 아래에 다음 줄을 추가합니다.

implementation 'com.google.code.gson:gson:2.8.1'

이후 버전을 확인할 수 있습니다.

그런 다음 프로젝트를 동기화하면 Gson을 인스턴스화하여 시작합니다.

        Gson gson = new Gson();

그런 다음 SharedPreferences를 가져옵니다.

        SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);

그런 다음 SharedPreferences 클래스의 edit() 메서드를 호출하여 SharedPreference.Editor 객체를 얻습니다.

        SharedPreferences.Editor editor = pref.edit();

그런 다음 Gson 클래스의 toJson() 메서드를 사용하여 객체를 JSON으로 변환합니다. 그런 다음 해당 JSON 데이터를 SharedPreference.Editor 인스턴스의 키와 함께 놓고 apply() 메서드를 호출합니다.

        editor.putString(key, gson.toJson(object));
        editor.apply();

Categorized in: