how to properly pack a List<Hashtable<String,List<String>>> in an Intent for broadcast?
On Andr开发者_C百科oid, I am trying to send a custom broadcast message using a custom Intent and BroadcastListeners. I have some custom data, in the format:
List<Hashtable<String,List<String>>> data;
When trying to use:
intent.putExtra("mydata", data);
I get the error:
The method putExtra(String, boolean) in the type Intent is not applicable for the arguments (String, List<Hashtable<String,List<String>>>)
Looking at the Intent class, there are a bunch of public methods that overload putExtra(). However, none seem to meet the data that I am trying to send.
There seem to be a rather generic method
putExtra(String name, Bundle value)
However, I am not sure how to transform my data in to a Bundle to use this. Is this the right thing to do? Or is there a simpler method?
You want to have Serializable for putExtra(String name, Serializable s)
version. However, List
is an interface that does not extend Serializable
. Try to declare it as ArrayList
.
I used to meet the some problem. I solved it in a ugly way I think, you can take it as a reference.
I put a Map
into a global singleton object, the key of Map
is String
, the Map
will keep the object I want to pass into Intent
, instead of putting the object into Intent
, I put the String
key into the Intent
. In the Activity
(or Service ...) where the intent was passed to, I get the key from Intent
, and then get the object which I really care about from the Mao
.
Maybe that's not clearly enough, here is pseudo code:
public void sendIntent() {
Object data; // the object you want to pass through Intent
Map<String, Object> globalMap = getMyGlobalMap();
String uid = UUID.randomUUID().toString();
globalMap.put(uid, data);
intent.putExtra(EXTRA_OBJECT_UID, uid);
}
public void receiveIntent() {
String uid = intent.getStringExtra(EXTRA_OBJECT_UID);
Object data = getMyGlobalMap().get(uid); // Here is your data object.
}
Note that, since you put the global map in a singleton object, you may want to remove the object from the Map
when you done with it, because the map will be there as long as your application live, you may not want to keep some useless objects and let them take your precious memory.
Update
Another very important thing is, the component which send the Intent and the component which will receive the Intent must be in the same process, only the classes in same process can share data in heap.
精彩评论