HashMap.EntrySet()
returns an ICollection
and items of that collection that can not be cast to an IMapEntry
.... issue? probably, but the root issue is trying to use Java generics in C# and thus a non-generic EntrySet()
should return a list of HashMap.SimpleEntry (or SimpleImmutableEntry) but is not mapped that way in Xamarin.Android
...
I work around this by using the the Xamarin.Android
runtime JavaDictionary (Android.Runtime.JavaDictionary
) as you can "cast" a Hashmap
to its generic version and act upon it as a normal C# generic class.
Assuming you are creating or receiving a simple HashMap
key/value (lots of the Google Android APIs use simple HashMaps to convert to Json for their Rest APIs, i.e. the Google Android Drive API makes use of a lot of HashMaps)
Create a Java HashMap (this is from a POCO or POJO):
var map = new HashMap();
map.Put(nameof(uuid), uuid);
map.Put(nameof(name), name);
map.Put(nameof(size), size);
Create a JavaDictionary
from the Handle
of a Hashmap
:
var jdictionaryFromHashMap = new Android.Runtime.JavaDictionary<string, string>(map.Handle, Android.Runtime.JniHandleOwnership.DoNotRegister);
Iterate the JavaDictionary
:
foreach (KeyValuePair<string, string> item in jdictionaryFromHashMap)
{
Log.Debug("SO", $"{item.Key}:{item.Value}");
}
Use Linq to create your C# Dictionary:
var dictionary = jdictionaryFromHashMap.ToDictionary(t => t.Key, t => t.Value);