デバッグ用とかクラッシュレポート用に SharedPreferences の全ての値を文字列やJSONで取得できるとすごく便利です。
PreferenceManager#getSharedPreferencesは ApplicationContext を渡さないと
メモリリークの恐れがあるらしいです。
そのためラッパーを用意してラッパー経由で SharedPreferences を取得します。
public static SharedPreferences getDefaultSharedPreferences(Context context){
return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
}
public static String toString(Context context){
return getDefaultSharedPreferences(context).getAll().toString();
}上記のメソッドで以下のように SharedPreferences の全ての値を文字列として取得することができます。{key1=value1, key2=value2}
public static String toJsonString(Context context) throws JSONException{
SharedPreferences preferences = getDefaultSharedPreferences(mContext);
JSONObject preferencesJson = new JSONObject();
Map<String, ?> map = preferences.getAll();
try{
for(Entry<String, ?> entry : map.entrySet()){
preferencesJson.put(entry.getKey(), entry.getValue());
}
}catch(JSONException e){
e.printStackTrace();
}
return preferencesJson.toString();
}上記のメソッドで以下のように SharedPreferences の全ての値を JSON として取得することができます。{"key1": "value1", "key2": "value2"}
#toString の引数にインデントスペース数を渡すとインデントされた JSON が返ってきます。
僕は コマンドラインJSONプロセッサ jq をインスールする | DevAchieve で jq をインストールしているので
インデントせずに JSON 化しますが、インデントされた JSON も取得できるのは便利ですね。