0

I am looking for a way to convert PersistableBundle to Bundle in android. Is there any simpler way to do this? They both do not inherit from same class and hence i cannot typecast them.

Edit:

I found this way to copy

public static Bundle getBundleFromPersistableBundle(final PersistableBundle persistableBundle) {
    Bundle bundle = new Bundle();
    if(persistableBundle == null) {
        return null;
    }
    bundle.putAll(persistableBundle);
    return bundle;
}

1 Answers1

1

You can construct a Bundle from a PersistableBundle instance.

PersistableBundle pb = new PersistableBundle();
Bundle b = new Bundle(pb);

See the documentation for this constructor:

Constructs a Bundle containing a copy of the mappings from the given PersistableBundle. Does only a shallow copy of the PersistableBundle -- see deepCopy() if you don't want that.

Tim
  • 41,901
  • 18
  • 127
  • 145
  • I found a way to do this: public static Bundle getBundleFromPersistableBundle(final PersistableBundle persistableBundle) { Bundle bundle = new Bundle(); if(persistableBundle == null) { return null; } bundle.putAll(persistableBundle); return bundle; } – user2267399 Sep 11 '17 at 10:44
  • This code snippet will create & discard a Bundle unnecessarily if it's called with a `null` PersistableBundle argument. Check for the null argument *first,* and only allocate the Bundle if you are actually going to return one. – ctate Sep 28 '17 at 20:52
  • @ctate this code snippet also defines the PeristableBundle, so it is by definition not null – Tim Sep 28 '17 at 21:12
  • I'm referring to the snippet in user2267399's comment, not yours. Sorry for the ambiguity. – ctate Sep 29 '17 at 21:25
  • @ctate oh ok, no problem – Tim Sep 29 '17 at 21:27