Reads a Map from a Parcel that was stored using a String array and a Bundle. - Android Android OS

Android examples for Android OS:Parcel

Description

Reads a Map from a Parcel that was stored using a String array and a Bundle.

Demo Code


//package com.java2s;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.HashMap;
import java.util.Map;

public class Main {
    /**// w ww. j a va 2 s .c o m
     * Reads a Map from a Parcel that was stored using a String array and a Bundle.
     *
     * @param in   the Parcel to retrieve the map from
     * @param type the class used for the value objects in the map, equivalent to V.class before type erasure
     * @return a map containing the items retrieved from the parcel
     */
    public static <V extends Parcelable> Map<String, V> readMap(Parcel in,
            Class<? extends V> type) {

        Map<String, V> map = new HashMap<String, V>();
        if (in != null) {
            String[] keys = in.createStringArray();
            Bundle bundle = in.readBundle(type.getClassLoader());
            for (String key : keys)
                map.put(key, type.cast(bundle.getParcelable(key)));
        }
        return map;
    }

    /**
     * Reads into an existing Map from a Parcel that was stored using a String array and a Bundle.
     *
     * @param map  the Map<String,V> that will receive the items from the parcel
     * @param in   the Parcel to retrieve the map from
     * @param type the class used for the value objects in the map, equivalent to V.class before type erasure
     */
    public static <V extends Parcelable> void readMap(Map<String, V> map,
            Parcel in, Class<V> type) {

        if (map != null) {
            map.clear();
            if (in != null) {
                String[] keys = in.createStringArray();
                Bundle bundle = in.readBundle(type.getClassLoader());
                for (String key : keys)
                    map.put(key, type.cast(bundle.getParcelable(key)));
            }
        }
    }
}

Related Tutorials