개발 창고/Android

[Android] How to use SharedPreference

로이제로 2024. 2. 6. 07:59
반응형

 

There are many ways to store data in an Android app

Among them, Shared Preference is the simplest way to use it.


Example

public class MainActivity extends AppCompatActivity {
	private final PREF_KEY = "PREF_KEY";    // Key value to store data
    private SharedPreferences mPrefs;	    // Variables in storage

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Predefined for Storage Use
        mPrefs = getPreferences(MODE_PRIVATE);
        
        int value = this.getPrefInt(PREF_KEY, -1);
 		
        value = value + 1;
        
        this.setPrefInt(PREF_KEY, value);
        
    }
    
    // =================  Handle Data ======================= //

    /**
     * Return stored data
     */
    private int getPrefInt(String key, int defValue){
        return mPrefs.getInt(key, defValue);
    }

    /**
     * Save data
     */
    private void setPrefInt(String key, int value){
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        prefsEditor.putInt(key, value);
        prefsEditor.apply();
    }
    // =================  Handle Data ======================= //
}

 

Description

In my case, I usually declare it as a method

 

1. To use SharedPreferences within a class, use the name mPrefs to declare.

2. onCreate (When Activity is first created) create mPrefs to function as SharedPrefences.

    Tip 1. getPreferences() only works within the activity you are currently calling, you must utilize getSharedPreferences to call from other activities as well.

        ex) mPrefs = this.getPreference(Activity.MODE_PRIVATE);

              mPrefs = this.getSharedPreferences("PublicPrefKey", Context.MODE_PRIVATE);

    Tip 2. MODE_PRIVATE means limiting it to be used only in the part associated with the application called as a variable in the context. A function that existed since API Lev 1.

             종류:

             - MODE_APPEND

             - MODE_ENABLE_WRITE_AHEAD_LOGGING

             - MODE_MULTI_PROCESS

             - MODE_NO_LOCALIZED_COLLATORS

             - MODE_PRIVATE

             - MODE_WORLD_READABLE

             - MODE_WORLD_WRITABLE

            ❊Some modes have been deprecated by version, so please refer to the link below.

 

https://developer.android.com/reference/android/content/Context

 

Context  |  Android Developers

 

developer.android.com

 

3. I recommend creating and reusing getPrefInt and setPrefInt. (It's quite useful when making an app, so it's good to get into a habit.)


Android-SharedPreference

🇰🇷 Korean

2020.07.22 - [개발 창고/Android] - [Android] SharedPreference 활용하기

 

[Android] SharedPreference 활용하기

보통 안드로이드 어플 내에 데이터를 저장하는 방식에는 여러 가지가 있는데 그중에서 가장 간단하게 쓰이는 방식이 SharedPreference입니다. public class MainActivity extends AppCompatActivity { private final PREF_

royzero.tistory.com

 

반응형