Como posso salvar um HashMap nas preferências compartilhadas no Android?
Como posso salvar um HashMap nas preferências compartilhadas no Android?
Respostas:
Eu não recomendaria escrever objetos complexos em SharedPreference. Em vez disso, usaria ObjectOutputStreampara gravá-lo na memória interna.
File file = new File(getDir("data", MODE_PRIVATE), "map");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(map);
outputStream.flush();
outputStream.close();
Eu uso Gsonpara converter HashMappara Stringe, em seguida, salve-o emSharedPrefs
private void hashmaptest()
{
//create test hashmap
HashMap<String, String> testHashMap = new HashMap<String, String>();
testHashMap.put("key1", "value1");
testHashMap.put("key2", "value2");
//convert to string using gson
Gson gson = new Gson();
String hashMapString = gson.toJson(testHashMap);
//save in shared prefs
SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE);
prefs.edit().putString("hashString", hashMapString).apply();
//get from shared prefs
String storedHashMapString = prefs.getString("hashString", "oopsDintWork");
java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> testHashMap2 = gson.fromJson(storedHashMapString, type);
//use values
String toastString = testHashMap2.get("key1") + " | " + testHashMap2.get("key2");
Toast.makeText(this, toastString, Toast.LENGTH_LONG).show();
}
Eu escrevi um código simples para salvar o mapa de preferência e carregar o mapa de preferência. Nenhuma função GSON ou Jackson necessária. Acabei de usar um mapa com String como chave e Boolean como valor.
private void saveMap(Map<String,Boolean> inputMap){
SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
Editor editor = pSharedPref.edit();
editor.remove("My_map").commit();
editor.putString("My_map", jsonString);
editor.commit();
}
}
private Map<String,Boolean> loadMap(){
Map<String,Boolean> outputMap = new HashMap<String,Boolean>();
SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Boolean value = (Boolean) jsonObject.get(key);
outputMap.put(key, value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
getApplicationContextpartir de uma aula simples?
Map<String, String> aMap = new HashMap<String, String>();
aMap.put("key1", "val1");
aMap.put("key2", "val2");
aMap.put("Key3", "val3");
SharedPreferences keyValues = getContext().getSharedPreferences("Your_Shared_Prefs"), Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : aMap.keySet()) {
keyValuesEditor.putString(s, aMap.get(s));
}
keyValuesEditor.commit();
Como um desdobramento da resposta de Vinoj John Hosan, eu modifiquei a resposta para permitir inserções mais genéricas, com base na chave dos dados, em vez de uma única chave como "My_map" .
Na minha implementação, MyAppé minha Applicationclasse de substituição e MyApp.getInstance()atua para retornar o context.
public static final String USERDATA = "MyVariables";
private static void saveMap(String key, Map<String,String> inputMap){
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
if (pSharedPref != null){
JSONObject jsonObject = new JSONObject(inputMap);
String jsonString = jsonObject.toString();
SharedPreferences.Editor editor = pSharedPref.edit();
editor.remove(key).commit();
editor.putString(key, jsonString);
editor.commit();
}
}
private static Map<String,String> loadMap(String key){
Map<String,String> outputMap = new HashMap<String,String>();
SharedPreferences pSharedPref = MyApp.getInstance().getSharedPreferences(USERDATA, Context.MODE_PRIVATE);
try{
if (pSharedPref != null){
String jsonString = pSharedPref.getString(key, (new JSONObject()).toString());
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keysItr = jsonObject.keys();
while(keysItr.hasNext()) {
String k = keysItr.next();
String v = (String) jsonObject.get(k);
outputMap.put(k,v);
}
}
}catch(Exception e){
e.printStackTrace();
}
return outputMap;
}
Contextinstância de uma biblioteca. Confira esta outra pergunta do SO: É possível obter o contexto do aplicativo em um projeto de biblioteca do Android?
Você pode tentar usar JSON.
Para salvar
try {
HashMap<Integer, String> hash = new HashMap<>();
JSONArray arr = new JSONArray();
for(Integer index : hash.keySet()) {
JSONObject json = new JSONObject();
json.put("id", index);
json.put("name", hash.get(index));
arr.put(json);
}
getSharedPreferences(INSERT_YOUR_PREF).edit().putString("savedData", arr.toString()).apply();
} catch (JSONException exception) {
// Do something with exception
}
Para obter
try {
String data = getSharedPreferences(INSERT_YOUR_PREF).getString("savedData");
HashMap<Integer, String> hash = new HashMap<>();
JSONArray arr = new JSONArray(data);
for(int i = 0; i < arr.length(); i++) {
JSONObject json = arr.getJSONObject(i);
hash.put(json.getInt("id"), json.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
String converted = new Gson().toJson(map);
SharedPreferences sharedPreferences = getSharedPreferences("sharepref",Context.MODE_PRIVATE);
sharedPreferences.edit().putString("yourkey",converted).commit();
Usando PowerPreference .
Guardar dados
HashMap<String, Object> hashMap = new HashMap<String, Object>();
PowerPreference.getDefaultFile().put("key",hashMap);
Ler dados
HashMap<String, Object> value = PowerPreference.getDefaultFile().getMap("key", HashMap.class, String.class, Object.class);
mapa -> string
val jsonString: String = Gson().toJson(map)
preferences.edit().putString("KEY_MAP_SAVE", jsonString).apply()
string -> mapa
val jsonString: String = preferences.getString("KEY_MAP_SAVE", JSONObject().toString())
val listType = object : TypeToken<Map<String, String>>() {}.type
return Gson().fromJson(jsonString, listType)
Você pode usar isso em um arquivo dedicado em preferências compartilhadas (fonte: https://developer.android.com/reference/android/content/SharedPreferences.html ):
getAll
adicionado na API nível 1 Mapa getAll () Recupera todos os valores das preferências.
Observe que você não deve modificar a coleção retornada por este método, ou alterar qualquer um de seus conteúdos. A consistência dos seus dados armazenados não é garantida se você fizer isso.
Returns Map Retorna um mapa contendo uma lista de pares chave / valor que representam as preferências.
Para o caso de uso restrito, quando seu mapa não terá mais do que algumas dezenas de elementos, você pode aproveitar o fato de que SharedPreferences funciona quase como um mapa e simplesmente armazena cada entrada em sua própria chave:
Map<String, String> map = new HashMap<String, String>();
map.put("color", "red");
map.put("type", "fruit");
map.put("name", "Dinsdale");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// OR use a specific pref name
// context.getSharedPreferences("myMegaMap");
for (Map.Entry<String, String> entry : map.entrySet()) {
prefs.edit().putString(entry.getKey(), entry.getValue());
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// OR use a specific pref name
// context.getSharedPreferences("myMegaMap");
prefs.getString("color", "pampa");
No caso de você usar um nome de preferência personalizado (ou seja context.getSharedPreferences("myMegaMap")), você também pode obter todas as chaves comprefs.getAll()
Seus valores podem ser de qualquer tipo suportado pelo SharedPreferences:
String,int,long,float,boolean.
Eu sei que é um pouco tarde, mas espero que isso possa ser útil para qualquer leitura ..
então o que eu faço é
1) Crie HashMap e adicione dados como: -
HashMap hashmapobj = new HashMap();
hashmapobj.put(1001, "I");
hashmapobj.put(1002, "Love");
hashmapobj.put(1003, "Java");
2) Escreva no editor de preferências de compartilhamento como: -
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
Editor editor = sharedpreferences.edit();
editor.putStringSet("key", hashmapobj );
editor.apply(); //Note: use commit if u wan to receive response from shp
3) Lendo dados como: - em uma nova classe onde você deseja que sejam lidos
HashMap hashmapobj_RECIVE = new HashMap();
SharedPreferences sharedPreferences (MyPREFERENCES,Context.MODE_PRIVATE;
//reading HashMap from sharedPreferences to new empty HashMap object
hashmapobj_RECIVE = sharedpreferences.getStringSet("key", null);