Android How to put Map<V,T> in an intent
android, android-intent
Solution
You can put a serializable as extra [1]. And HashMap for example does implement the serializable interface [2]. So if you change your variable type from Map to HashMap you can put your map directly as extra.
[1] http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String,%20java.io.Serializable) [2] https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Problem
I have a `Map` object and I want to put it in an intent to start a `Service`: ``` Map<Integer, String> modules = new HashMap<Integer, String>(); Intent downloadServiceIntent = new Intent(context.getApplicationContext(), DownloadService.class); downloadServiceIntent.putExtra("EXTRA_MODULE", modules); context.startService(downloadServiceIntent); ``` I think I could break the `Map` into two arrays (`int[]` and `String[]`), then put them in intent. For example: ``` int[] keys = new int[modules.size()]; String[] values = new String[modules.size()]; int i = 0; for (Map.Entry<Integer, String> entry : modules.entrySet()) { keys[i] = entry.getKey(); values[i] = entry.getValue(); i++; } downloadServiceIntent.putExtra("EXTRA_KEYS", keys); downloadServiceIntent.putExtra("EXTRA_VALUES", values); ``` Is it a good idea? Is there any alternative ways to achieve this?