안드로이드 개발자 사이트에 가시면 관련 예제들이 있습니다. https://developer.android.com/training/data-storage/shared-preferences
public interface Storage {
public int getInt(key, defaultValue);
public void setInt(key, value);
//필요에 따라 get/setString, get/setLong, get/setFloat, get/setDouble, get/setBoolean 추가
}
public class PrefStorage implements Storage {
private final SharedPreferences sharedPref;
public PrefStorage(Context context) {
sharedPref = context.getPreferences(Context.MODE_PRIVATE);
}
public int getInt(key, defaultValue) {
return sharedPref.get(key, defaultValue);
}
public void setInt(key, value) {
sharedPref.edit()
.putInt(key, value)
.apply();
}
}
public interface Settings {
public int getLastSelectedTextPosition();
public int setLastSelectedTextPosition(int value);
}
public class AppSettings implements Settings {
private static final YOU_KEY_NAME = "your_key_name"
private final Storage storage;
public AppSettings(Storage storage) {
this.storage = storage;
}
private int public int getLastSelectedTextPosition() {
return storage.getInt(YOU_KEY_NAME, 0);
}
public int setLastSelectedTextPosition(int value) {
storage.putInt(YOU_KEY_NAME, value);
}
}
//Activity
private Settings settings;
public void onCrate(...) {
super.onCreate(...);
initViewState();
}
private void initViewState() {
settings = new AppSettings(new PrefStorage(geApplicationContext());
val lastPosition= settings.getLastSelectedTextPosition();
button.setText(getButtonText(lastPosition));
}
스토리지에 엑세스하거나 하는 등의 클래스, 보통은 다른 레이어라고 부르는데, 이런 클래스들은 인터페이스를 통해 작업하시는게 원칙입니다. 이렇게 하는 이유는 종속성을 줄이는 겁니다. 나중에 변경사항이 생기거나 하면 훨씬 대처가 쉬워요. 예를 들면 지금은 sharedpreference를 사용하지만 추후에 db를 대신 사용하라고 할 수도 있고, 변경 사항이 생겨도 인터페이스는 수정하지 않고 구현부분만 수정할 수 있기 때문에 훨씬 유연한 구조죠.
그리고 이런 객체는 싱글톤을, 즉 어플리케이션에 인스턴스가 하나만 존재하는 게 낫구요, 그렇게 하려면 Application 클래스를 상속받아서 onCreate에 초기화를 해주고 글로벌하게 액세스할 수 있도록 해주면 됩니다. 이 부분은 길어지므로 별도로 공부하시길 바랍니다. 그리고 배열에 텍스트 배열과 인덱스를 맵핑하는 부분도 아주 간단한 부분이니 직접 마무리해 보시길 바래요.
그럼, 도움이 되시길.