Menu Docs
Página inicial do Docs
/ /
Tipos de dados

RealmDictionary - SDK Java

Novidade na versão 10.6.0.

Você pode usar o tipo de dados RealmDictionary para gerenciar uma collection de chaves String únicas emparelhadas com valores. RealmDictionary implementa a interface Map do Java , portanto, funciona como a classe HashMap incorporada , exceto pelo fato de que as instâncias RealmDictionary gerenciadas persistem seu conteúdo em um Realm. As instâncias RealmDictionary que contêm objetos de Realm armazenam referências a esses objetos. Quando você exclui um Objeto de Realm de um Realm, quaisquer referências a esse objeto em um RealmDictionary se tornam null valores.

Para criar um campo do tipo RealmDictionary, defina uma propriedade de objeto do tipo RealmDictionary<T>, onde T define os valores que você gostaria de armazenar em seu RealmDictionary. Atualmente, instâncias RealmDictionary só podem usar chaves do tipo String.

A tabela a seguir mostra quais métodos você pode usar para concluir tarefas de collection comuns com RealmDictionary:

Tarefa
Método

Adicionar um objeto a um RealmDictionary

put() (ou o operador [] em Kotlin)

Adicionar vários objetos a um RealmDictionary

Verificar se o dicionário contém uma chave específica

Verificar se o dicionário contém um valor específico

import io.realm.RealmDictionary;
import io.realm.RealmObject;
public class Frog extends RealmObject {
String name;
RealmDictionary<Frog> nicknamesToFriends;
// realm-required empty constructor
public Frog() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public RealmDictionary<Frog> getNicknamesToFriends() { return nicknamesToFriends; }
public void setNicknamesToFriends(RealmDictionary<Frog> nicknamesToFriends) { this.nicknamesToFriends = nicknamesToFriends; }
}
Frog frog = realm.createObject(Frog.class);
frog.setName("George Washington");
// get the RealmDictionary field from the object we just created
RealmDictionary<Frog> dictionary = frog.getNicknamesToFriends();
// add key/value to the dictionary
Frog wirt = realm.createObject(Frog.class);
wirt.setName("Wirt");
dictionary.put("tall frog", wirt);
// add multiple keys/values to the dictionary
Frog greg = realm.createObject(Frog.class);
greg.setName("Greg");
Frog beatrice = realm.createObject(Frog.class);
beatrice.setName("Beatrice");
dictionary.putAll(Map.of("small frog", greg, "feathered frog", beatrice));
// check for the presence of a key
Assert.assertTrue(dictionary.containsKey("small frog"));
// check for the presence of a value
Assert.assertTrue(dictionary.containsValue(greg));
// remove a key
dictionary.remove("feathered frog");
Assert.assertFalse(dictionary.containsKey("feathered frog"));
// deleting a Realm object does NOT remove it from the dictionary
int sizeOfDictionaryBeforeDelete = dictionary.size();
greg.deleteFromRealm();
// deleting greg object did not reduce the size of the dictionary
Assert.assertEquals(sizeOfDictionaryBeforeDelete, dictionary.size());
// but greg object IS now null:
Assert.assertEquals(dictionary.get("small frog"), null);
import io.realm.RealmDictionary
import io.realm.RealmObject
open class Frog
: RealmObject() {
var name: String? = null
var nicknamesToFriends: RealmDictionary<Frog> = RealmDictionary<Frog>()
}
val frog =
realm.createObject(Frog::class.java)
frog.name = "George Washington"
// get the RealmDictionary field from the object we just created
val dictionary = frog.nicknamesToFriends
// add key/value to the dictionary
val wirt =
realm.createObject(Frog::class.java)
wirt.name = "Wirt"
dictionary["tall frog"] = wirt
// add multiple keys/values to the dictionary
val greg =
realm.createObject(Frog::class.java)
greg.name = "Greg"
val beatrice =
realm.createObject(Frog::class.java)
beatrice.name = "Beatrice"
dictionary.putAll(mapOf<String, Frog>(
Pair("small frog", greg),
Pair("feathered frog", beatrice)))
// check for the presence of a key
Assert.assertTrue(dictionary.containsKey("small frog"))
// check for the presence of a value
Assert.assertTrue(dictionary.containsValue(greg))
// remove a key
dictionary.remove("feathered frog")
Assert.assertFalse(dictionary.containsKey("feathered frog"))
// deleting a Realm object does NOT remove it from the dictionary
val sizeOfDictionaryBeforeDelete = dictionary.size
greg.deleteFromRealm()
// deleting greg object did not reduce the size of the dictionary
Assert.assertEquals(
sizeOfDictionaryBeforeDelete.toLong(),
dictionary.size.toLong()
)
// but greg object IS now null:
Assert.assertEquals(dictionary["small frog"], null)

Para assinar alterações em um RealmDictionary, passe uma implementação do MapChangeListener para o RealmSet.addChangeListener método. Sua implementação MapChangeListener deve definir um método onChange() , que aceita uma referência ao RealmDictionary alterado e um conjunto de alterações como parâmetros. Você pode acessar as chaves adicionadas ao dicionário, bem como as chaves removidas do dicionário por meio do parâmetro MapChangeSet .

AtomicReference<Frog> frog = new AtomicReference<Frog>();
realm.executeTransaction(r -> {
frog.set(realm.createObject(Frog.class));
frog.get().setName("Jonathan Livingston Applesauce");
});
MapChangeListener<String, Frog> mapChangeListener =
new MapChangeListener<String, Frog>() {
@Override
public void onChange(RealmMap<String, Frog> map,
MapChangeSet<String> changes) {
for (String insertion : changes.getInsertions()) {
Log.v("EXAMPLE",
"Inserted key: " + insertion +
", Inserted value: " + map.get(insertion).getName());
}
}
};
frog.get().getNicknamesToFriends().addChangeListener(mapChangeListener);
realm.executeTransaction(r -> {
// get the RealmDictionary field from the object we just created
RealmDictionary<Frog> dictionary = frog.get().getNicknamesToFriends();
// add key/value to the dictionary
Frog wirt = realm.createObject(Frog.class);
wirt.setName("Wirt");
dictionary.put("tall frog", wirt);
// add multiple keys/values to the dictionary
Frog greg = realm.createObject(Frog.class);
greg.setName("Greg");
Frog beatrice = realm.createObject(Frog.class);
beatrice.setName("Beatrice");
dictionary.putAll(Map.of("small frog", greg, "feathered frog", beatrice));
});
var frog: Frog? = null
realm.executeTransaction { r: Realm? ->
frog = realm.createObject(Frog::class.java)
frog?.name = "Jonathan Livingston Applesauce"
}
val mapChangeListener: MapChangeListener<String, Frog>
= MapChangeListener<String, Frog> { map, changes ->
for (insertion in changes.insertions) {
Log.v("EXAMPLE",
"Inserted key: $insertion, Inserted value: ${map[insertion]!!.name}")
}
}
frog?.nicknamesToFriends?.addChangeListener(mapChangeListener)
realm.executeTransaction { r: Realm? ->
// get the RealmDictionary field from the object we just created
val dictionary = frog!!.nicknamesToFriends
// add key/value to the dictionary
val wirt = realm.createObject(Frog::class.java)
wirt.name = "Wirt"
dictionary["tall frog"] = wirt
// add multiple keys/values to the dictionary
val greg = realm.createObject(Frog::class.java)
greg.name = "Greg"
val beatrice = realm.createObject(Frog::class.java)
beatrice.name = "Beatrice"
dictionary.putAll(mapOf<String, Frog>(
Pair("small frog", greg),
Pair("feathered frog", beatrice)))
}

Voltar

Contadores

Nesta página