Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two Bundle objects are equal in Android?

Tags:

android

bundle

I would like to check if two bundles are equal, is there any way to do that instead of checking them key by key?

like image 225
pixel Avatar asked Nov 05 '12 15:11

pixel


2 Answers

I have tested Sam's answer and it contains a flaw. Plus I am loving Kotlin at the moment, so here is my version.

  • Again the keys sets need to be the same size
  • The key sets need to have the same values
  • If both values are Bundle then test recursively.
  • Otherwise test values for equality (don't retest bundles)

Code:

fun equalBundles(one: Bundle, two: Bundle): Boolean {
    if (one.size() != two.size())
        return false

    if (!one.keySet().containsAll(two.keySet()))
        return false

    for (key in one.keySet()) {
        val valueOne = one.get(key)
        val valueTwo = two.get(key)
        if (valueOne is Bundle && valueTwo is Bundle) {
            if (!equalBundles(valueOne , valueTwo)) return false
        } else if (valueOne != valueTwo) return false
    }

    return true
}
like image 176
Simon Featherstone Avatar answered Sep 16 '22 12:09

Simon Featherstone


private static boolean equalsBundles(Bundle a, Bundle b) {
        Set<String> aks = a.keySet();
        Set<String> bks = b.keySet();

        if (!aks.containsAll(bks)) {
            return false;
        }

        for (String key : aks) {
            if (!a.get(key).equals(b.get(key))) {
                return false;
            }
        }

        return true;
    }
like image 36
Ivan Avatar answered Sep 17 '22 12:09

Ivan