I am trying to create helper method that would iterate through all Bundle objects, in a generic manner.
By "generic" I mean:
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?
The get (String key) method of Bundle returns an Object. Your best bet is to spin over the key set calling get (String) on each key and using toString () on the Object to output them. This will work best for primitives, but you may run into issues with Objects that do not implement a toString (). Show activity on this post.
Initially iterator points to the first element. Keep incrementing iterator till the last element of the list. To make iterator point to beginning and iterate till the end of the list Let’s see the below program to understand it clearly. Similarly an STL algorithm i.e. std::for_each accepts a range and a function,
The most straightforward way to loop through an object's properties is by using the for...in statement. This method works in all modern and old browsers including Internet Explorer 6 and higher. Here is an example that uses the for...in loop to iterate over an object:
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.
I would do it through reflection, if I were to do it at all. Store a static Map such that String.class maps to SharedPreference.putString(), etc. Then, when you're looping through the items check their class against the map. If it doesn't exist, check the superclass, etc. That will either give you the proper method to call or will let you know that the requested object's type isn't something that can be put into the preferences.
So the basic algorithm is:
Note: reflection isn't fast and it isn't the easiest thing to code and maintain. If at all possible I'd recommend finding a less generic method that fits your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With