Read a HashMap from a Parcel, class of key and value can parcelable both - Android android.os

Android examples for android.os:Parcel

Description

Read a HashMap from a Parcel, class of key and value can parcelable both

Demo Code


//package com.java2s;
import java.util.HashMap;
import java.util.Map;

import android.os.Parcel;
import android.os.Parcelable;

public class Main {
    /**// w ww  . ja va  2  s. c o m
     * Read a HashMap from a Parcel, class of key and value can parcelable both
     *
     * @param <V>
     * @param in
     * @param loader
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <K extends Parcelable, V extends Parcelable> Map<K, V> readHashMap(
            Parcel in, ClassLoader loader) {
        if (in == null) {
            return null;
        }

        int size = in.readInt();
        if (size == -1) {
            return null;
        }

        Map<K, V> map = new HashMap<K, V>();
        for (int i = 0; i < size; i++) {
            map.put((K) in.readParcelable(loader),
                    (V) in.readParcelable(loader));
        }
        return map;
    }
}

Related Tutorials