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
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' 카테고리의 다른 글
[Android] How to make round box (62) | 2024.02.13 |
---|---|
[Android] ActionBar 타이틀 변경과 뒤로가기 추가 - Kotlin (167) | 2024.02.07 |
[Android] 안드로이드 버전 확인 하는 방법 (188) | 2024.01.04 |
[Kotlin] How to use Kakao Navigation in my app (1) | 2023.12.14 |
[Kotlin] How to do Type Casting (1) | 2023.12.13 |