1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file 5 * except in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the 10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 11 * KIND, either express or implied. See the License for the specific language governing 12 * permissions and limitations under the License. 13 */ 14 15 package com.android.egg.neko; 16 17 import android.content.Context; 18 import android.content.SharedPreferences; 19 import android.content.SharedPreferences.OnSharedPreferenceChangeListener; 20 21 import java.util.ArrayList; 22 import java.util.List; 23 import java.util.Map; 24 25 public class PrefState implements OnSharedPreferenceChangeListener { 26 27 private static final String FILE_NAME = "mPrefs"; 28 29 private static final String FOOD_STATE = "food"; 30 31 private static final String CAT_KEY_PREFIX = "cat:"; 32 33 private final Context mContext; 34 private final SharedPreferences mPrefs; 35 private PrefsListener mListener; 36 37 public PrefState(Context context) { 38 mContext = context; 39 mPrefs = mContext.getSharedPreferences(FILE_NAME, 0); 40 } 41 42 // Can also be used for renaming. 43 public void addCat(Cat cat) { 44 mPrefs.edit() 45 .putString(CAT_KEY_PREFIX + String.valueOf(cat.getSeed()), cat.getName()) 46 .commit(); 47 } 48 49 public void removeCat(Cat cat) { 50 mPrefs.edit() 51 .remove(CAT_KEY_PREFIX + String.valueOf(cat.getSeed())) 52 .commit(); 53 } 54 55 public List<Cat> getCats() { 56 ArrayList<Cat> cats = new ArrayList<>(); 57 Map<String, ?> map = mPrefs.getAll(); 58 for (String key : map.keySet()) { 59 if (key.startsWith(CAT_KEY_PREFIX)) { 60 long seed = Long.parseLong(key.substring(CAT_KEY_PREFIX.length())); 61 Cat cat = new Cat(mContext, seed); 62 cat.setName(String.valueOf(map.get(key))); 63 cats.add(cat); 64 } 65 } 66 return cats; 67 } 68 69 public int getFoodState() { 70 return mPrefs.getInt(FOOD_STATE, 0); 71 } 72 73 public void setFoodState(int foodState) { 74 mPrefs.edit().putInt(FOOD_STATE, foodState).commit(); 75 } 76 77 public void setListener(PrefsListener listener) { 78 mListener = listener; 79 if (mListener != null) { 80 mPrefs.registerOnSharedPreferenceChangeListener(this); 81 } else { 82 mPrefs.unregisterOnSharedPreferenceChangeListener(this); 83 } 84 } 85 86 @Override 87 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 88 mListener.onPrefsChanged(); 89 } 90 91 public interface PrefsListener { 92 void onPrefsChanged(); 93 } 94 } 95