Muhamad Saad Nurul Ishlah, M.Comp.
Program Studi Sistem Informasi, Sekolah Vokasi,
Universitas Pakuan
Tipe penyimpanan data yang memungkinkan membaca (mengembalikan) dan menulis (menyimpan) data primitif sebagai pasangan kunci/nilai (key/value) pada sebuah berkas di penyimpanan perangkat
kelas SharedPreferences menyediakan APIs untuk membaca, menulis, dan mengatur data
Simpan data di metode callback onPause(), kembalikan data di onCreate()
Shared Prefernces | Saved Instance State |
---|---|
Menyimpan data di seluruh sesi pengguna, bahkan jika aplikasi mati dan restart, atau perangkat di-boot ulang | Mempertahankan data status di seluruh instan Activity dalam sesi pengguna yang sama |
Data yang harus diingat di seluruh sesi, seperti pengaturan yang disukai pengguna atau skor permainan mereka | Data yang tidak boleh diingat di seluruh sesi, seperti tab yang saat ini dipilih atau keadaan aktivitas saat ini. |
Secara umum digunakan untuk menyimpan preferensi pengguna | Secara umum digunakan untuk membuat ulang state setelah perangkat diputar |
private String sharedPrefFile =
"com.example.android.hellosharedprefs";
mPreferences =
getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.putInt("count", mCount);
preferencesEditor.putInt("color", mCurrentColor);
preferencesEditor.apply();
}
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
if (savedInstanceState != null) {
mCount = mPreferences.getInt("count", 1);
mShowCount.setText(String.format("%s", mCount));
mCurrentColor = mPreferences.getInt("color", mCurrentColor);
mShowCount.setBackgroundColor(mCurrentColor);
mNewText = mPreferences.getString("text", "");
} else { … }
SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
Implementasi interface SharedPreference.OnSharedPreferenceChangeListener
Daftarkan listener dengan registerOnSharedPreferenceChangeListener()
Daftarkan and hentikan listener dalam onResume() dan onPause()
Implementasikan pada callback onSharedPreferenceChanged()
public class SettingsActivity extends AppCompatActivity
implements OnSharedPreferenceChangeListener {
...
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals(MY_KEY)) {
// Do something
}
}
// Instansiasi listener
SharedPreferences.OnSharedPreferenceChangeListener listener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// Implementasikan listener di sini
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
}
Ketika mendaftarkan listener, pengatur preferensi tidak menyimpan referensi yang kuat ke listener
Anda harus menyimpan referensi yang kuat (strong reference) ke listener, jika tidak, listener tersebut akan rentan terhadap garbage collector
Simpan referensi ke listener dalam data instan dari sebuah objek yang akan ada selaman listener itu diperlukan
/*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.hellosharedprefs;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
/**
* HelloSharedPrefs is an adaptation of the HelloToast app from chapter 1.
* It includes:
* - Buttons for changing the background color.
* - Maintenance of instance state.
* - Themes and styles.
* - Read and write shared preferences for the current count and the color.
* <p>
* This is the solution code for HelloSharedPrefs.
*/
public class MainActivity extends AppCompatActivity {
// Current count
private int mCount = 0;
// Current background color
private int mColor;
// Text view to display both count and color
private TextView mShowCountTextView;
// Key for current count
private final String COUNT_KEY = "count";
// Key for current color
private final String COLOR_KEY = "color";
// Shared preferences object
private SharedPreferences mPreferences;
// Name of shared preferences file
private String sharedPrefFile =
"com.example.android.hellosharedprefs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views, color, preferences
mShowCountTextView = findViewById(R.id.count_textview);
mColor = ContextCompat.getColor(this,
R.color.default_background);
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
// Restore preferences
mCount = mPreferences.getInt(COUNT_KEY, 0);
mShowCountTextView.setText(String.format("%s", mCount));
mColor = mPreferences.getInt(COLOR_KEY, mColor);
mShowCountTextView.setBackgroundColor(mColor);
}
/**
* Handles the onClick for the background color buttons. Gets background
* color of the button that was clicked, and sets the TextView background
* to that color.
*
* @param view The view (Button) that was clicked.
*/
public void changeBackground(View view) {
int color = ((ColorDrawable) view.getBackground()).getColor();
mShowCountTextView.setBackgroundColor(color);
mColor = color;
}
/**
* Handles the onClick for the Count button. Increments the value of the
* mCount global and updates the TextView.
*
* @param view The view (Button) that was clicked.
*/
public void countUp(View view) {
mCount++;
mShowCountTextView.setText(String.format("%s", mCount));
}
/**
* Handles the onClick for the Reset button. Resets the global count and
* background variables to the defaults and resets the views to those
* default values.
*
* @param view The view (Button) that was clicked.
*/
public void reset(View view) {
// Reset count
mCount = 0;
mShowCountTextView.setText(String.format("%s", mCount));
// Reset color
mColor = ContextCompat.getColor(this,
R.color.default_background);
mShowCountTextView.setBackgroundColor(mColor);
// Clear preferences
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
}
/**
* Callback for activity pause. Shared preferences are saved here.
*/
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt(COUNT_KEY, mCount);
preferencesEditor.putInt(COLOR_KEY, mColor);
preferencesEditor.apply();
}
}
Video Tutorial
Diterjemahkan dari slide Android Developer Fundamentasl V2: Shared Preferences
Stackoverflow