Created
November 14, 2015 00:14
-
-
Save hrules6872/6237f3bb1485a2aadae6 to your computer and use it in GitHub Desktop.
PreferencesObjectHelper - Store and retrieve a class object in SharedPreferences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PreferencesObjectHelper<T> { | |
private static final String TAG = "PreferencesObjectHelper"; | |
private final SharedPreferences preferences; | |
private final SharedPreferences.Editor editor; | |
@SuppressLint("CommitPrefEdits") | |
public PreferencesObjectHelper(Context context, String fileName) { | |
preferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE); | |
editor = preferences.edit(); | |
} | |
public boolean put(String key, T value) { | |
try { | |
ByteArrayOutputStream byteArrayOutputStream; | |
byteArrayOutputStream = new ByteArrayOutputStream(); | |
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); | |
objectOutputStream.writeObject(value); | |
byte[] byteArray = byteArrayOutputStream.toByteArray(); | |
objectOutputStream.close(); | |
byteArrayOutputStream.close(); | |
byteArrayOutputStream = new ByteArrayOutputStream(); | |
Base64OutputStream base64OutputStream = | |
new Base64OutputStream(byteArrayOutputStream, Base64.DEFAULT); | |
base64OutputStream.write(byteArray); | |
base64OutputStream.close(); | |
byteArrayOutputStream.close(); | |
editor.putString(key, new String(byteArrayOutputStream.toByteArray())).commit(); | |
return true; | |
} catch (NotSerializableException e) { | |
Log.e(TAG, "NotSerializableException", e); | |
} catch (Exception e) { | |
Log.e(TAG, "UnknownException", e); | |
} | |
return false; | |
} | |
public T get(String key, T defValue) { | |
byte[] bytes = preferences.getString(key, "").getBytes(); | |
if (bytes.length == 0) { | |
return defValue; | |
} | |
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); | |
Base64InputStream base64InputStream = | |
new Base64InputStream(byteArrayInputStream, Base64.DEFAULT); | |
try { | |
ObjectInputStream objectInputStream = new ObjectInputStream(base64InputStream); | |
return (T) (objectInputStream != null ? objectInputStream.readObject() : defValue); | |
} catch (Exception e) { | |
Log.e(TAG, "UnknownException", e); | |
} | |
return defValue; | |
} | |
public void remove(String key) { | |
editor.remove(key).commit(); | |
} | |
public void removeAll() { | |
editor.clear().commit(); | |
} | |
public boolean contains(String key) { | |
return preferences.contains(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment