Compares two android.os.Bundle Bundles to check for equality. - Android Android OS

Android examples for Android OS:Bundle

Description

Compares two android.os.Bundle Bundles to check for equality.

Demo Code


//package com.book2s;
import android.os.Bundle;
import android.support.annotation.Nullable;
import java.util.Set;

public class Main {
    /**/*from   ww  w . j  a va  2s  .c om*/
     * Compares two {@link android.os.Bundle Bundles} to check for equality.
     *
     * @param a the first {@link android.os.Bundle Bundle}
     * @param b the second {@link android.os.Bundle Bundle}
     * @return {@code true} if the two {@link android.os.Bundle Bundles} have identical contents, or are both null
     */
    public static boolean areEqual(@Nullable Bundle a, @Nullable Bundle b) {
        // equal if both null
        if (a == null && b == null)
            return true;

        // unequal if one is null
        if (a == null || b == null)
            return false;

        // check size
        if (a.size() != b.size())
            return false;

        // get key sets
        Set<String> bundleAKeys = a.keySet();
        Object valueA;
        Object valueB;

        // loop keys
        for (String key : bundleAKeys) {
            // check key exists in second bundle
            if (!b.containsKey(key))
                return false;

            // get values
            valueA = a.get(key);
            valueB = b.get(key);

            // check null valued entries
            if (valueA == null && valueB == null)
                continue;
            if (valueA == null || valueB == null)
                return false;

            // compare iteratively if they are both bundles
            if (valueA instanceof Bundle && valueB instanceof Bundle) {
                if (!areEqual((Bundle) valueA, (Bundle) valueB))
                    return false;
                continue;
            }

            // check for different values
            if (!valueA.equals(valueB))
                return false;
        }

        // passed!
        return true;
    }
}

Related Tutorials