Check if two Bundle object are Equal recursively - Android android.os

Android examples for android.os:Bundle

Description

Check if two Bundle object are Equal recursively

Demo Code

import java.util.Set;

import android.os.Bundle;

public class Main {

  /**//from w  ww  . jav a  2 s . 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(Bundle a, 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