How to Iterate through all Bundle objects

ateiob picture ateiob · Aug 10, 2012 · Viewed 18.7k times · Source

I am trying to create helper method that would iterate through all Bundle objects, in a generic manner.

By "generic" I mean:

  1. Doesn't need to know the names (keys) of the objects in the Bundle passed as a parameter.
  2. Doesn't need to change if another member (key) was added to the Bundle in the future.

So far, I figure out the following outline to accomplish that:

  private void bundleToSharedPreferences(Bundle bundle) {
    Set<String> keys = bundle.keySet();
    for (String key : keys) {
        Object o = bundle.get(key);
        if (o.getClass().getName().contentEquals("int")) {
            // save ints
        }
        else if (o.getClass().getName().contentEquals("boolean")) {
            // save booleans
        }
        else if (o.getClass().getName().contentEquals("String")) {
            // save Strings
        }
        else {
            // etc.
        }
    } 
  }

Does this approach make sense at all?

Is there a better way of accomplishing this?

Answer

Daniel picture Daniel · Jun 11, 2013

Could you save everything as String using the toString() method? Don't know if primitive types are mapped to their Object equivalents (e.g. int to class Integer), but if they are, then you might be able to do something like this, instead of laboriously checking each possible class.

 for (String key : bundle.keySet()) {
        saveKeyValueInPrefs(key, bundle.get(key).toString()); //To Implement
 }

Not sure if this would work for your needs, but I'm trying to do something similar to convert a bundle into a JSON string right now.