Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the list of all extras from an Intent in Xamarin.Android and save it in a dictionary

I want to list all extras (and their values) of an Intent object and save them in a dictionary.

The first problem is I don't necessary know all the keys. The second problem is that some values are strings, some are boolean... and so on. How could I get the values in a loop (looping through the keys) and save the value in C# Xamarin.Android?

like image 450
Daniele D. Avatar asked Dec 06 '16 09:12

Daniele D.


3 Answers

LINQ variant

Bundle bundle = intent.Extras;
Dictionary<string, object> dict = bundle.KeySet()
    .ToDictionary<string, string, object>(key => key, key => bundle.Get(key));
like image 113
Dmitry Kasatsky Avatar answered Oct 22 '22 17:10

Dmitry Kasatsky


You could make this a convenient extension method as well:

public static Dictionary<string, string> ToDictionary(this Bundle bundle)
{
    var dictionary = new Dictionary<string, string>();
    foreach (var key in bundle.KeySet())
    {
      dictionary.Add(key, b.Get(key).ToString());
    }   
    return dictionary;
}
like image 42
SuavePirate Avatar answered Oct 22 '22 17:10

SuavePirate


Here what I found after a while and I'm going to share it so that someone else can save time.

//Didactic version
Bundle b = myIntent.Extras; //Where myIntent is of course an Intent
ICollection<string> c = b.KeySet(); //This is the collection of extras
Dictionary<string, string> d = new Dictionary<string, string>(); 

foreach (var key in c)
{
  Object value = b.Get(key);
  d.Add(key, value.ToString());
}   

//Short version
var b = myIntent.Extras; 
var d = new Dictionary<string, string>();

foreach (var key in b.KeySet();)
{
  d.Add(key, b.Get(key).ToString());
}   
like image 2
Daniele D. Avatar answered Oct 22 '22 15:10

Daniele D.