I want to read a map map
from the Database (Firebase),and i compare it to another map motcle
, if i find a duplicate key i increment the value of the key in map
,I am having a ClassCastException. the code:
public void addMotcle(final Map motcle, String Userid)
{
mDatabase = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference user = mDatabase.child(Userid);
final DatabaseReference keylist = user.child("motcle");
keylist.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
//I tried to put the map in another map and change it but
//It is still the same error
Map<String,Integer> map = (Map) dataSnapshot.getValue();
Map<String,Integer>Hmap= new HashMap<>();
Hmap.putAll(map);
//if there is duplicate we incremente les mots clé
for (Object key : motcle.keySet()) {
if (Hmap.containsKey(key)) {
Hmap.put((String)key,((Integer) Hmap.get(key))+1);
}
else
{
Hmap.put((String) key,1);
}
}
keylist.setValue(Hmap);
}
else
{
keylist.setValue(motcle);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Here is the Value that i want to write on in Firebase
the error is in the line map.put((String)key,map.get(key)+1);
why can't i write an Integer
in the value if i declared map
as Map<String,Integer>
?
When you do Map<String,Integer> map = (Map) dataSnapshot.getValue();
, you guarantee that map
is a Map
, but not that it's a Map<String, Integer>
. Since generics are erased and not available at runtime, as long as dataSnapshot.getValue()
is a Map
of some kind, this cast will succeed.
Because you've declared Hmap
as a Map<String,Integer>
, when you get a value from the map, it will try to cast it to Integer
, but there is nothing actually guaranteeing ahead-of-time that it will be an Integer. As a result, if the value is actually a Long
, it will try to cast that Long
to an Integer
and fail (because Long
does not extend Integer
, and widening operations don't work on boxed types).
You need to find out what the actual types of the values of dataSnapshot.getValue()
are, and cast it to the correct type of Map
to avoid this error.
See here for more details: Weird problem about Java Generics operation
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments