Here is the sample code for passing Object references between
activities:
I have a class called ReferencePasser, which wraps a HashMap:
import java.util.HashMap;
/**
* @author Amos
* Maps Objects to keys.
* The keys are generated automatically on insertion (based on a
running index).
* Useful for passing references to objects.
*/
public class ReferencePasser {
private HashMap<Long, Object> _objects;
private long _nextKey;
public ReferencePasser() {
_objects = new HashMap<Long, Object>();
_nextKey = 1;
}
/**
* Adds the given object to the map.
* @param o
* @return the key of object inserted.
*/
public long put(Object o) {
long key = _nextKey++;
_objects.put(Long.valueOf(key), o);
return key;
}
/**
* @param key
* @return the object with the given key, or null if
key doesn't
exist in
* the map.
*/
public Object get(long key) {
return _objects.get(Long.valueOf(key));
}
/**
* Removes the object mapped to the given key from the
map.
* @param key
*/
public void remove(long key) {
_objects.remove(Long.valueOf(key));
}
}
Access to a single instance of ReferencePasser is achived through this
class:
public class GlobalStuff {
private static ReferencePasser _passer;
/**
* Returns the application's ReferencePasser, which is
useful for
passing
* references to complex objects between Activities
and/or
Services.
* @return
*/
public static ReferencePasser getReferencePasser() {
if (_passer == null)
_passer = new ReferencePasser();
return _passer;
}
}
Here's a sample for an activity that wants to send an object to
another activity:
public class SourceActivity extends Activity {
...
private void startTargetActivity(SomeObject myObject) {
ReferencePasser passer =
GlobalStuff.getReferencePasser();
long objectKey = passer.put(myObject);
Intent intent = new Intent(this,
TargetActivity.class);
intent.putExtra("com.myapp.blabla", objectKey);
startActivity(intent);
}
...
}
And here's how the called activity gets the object that was passed to
it:
public class SourceActivity extends Activity {
protected void onCreate(Bundle icicle) {
//remember to handle null values, which I don't
do here
long objectKey =
getIntent().getLongExtra("com.myapp.blabla", 0);
ReferencePasser passer =
GlobalStuff.getReferencePasser();
SomeObject passedObject = (SomeObject)
passer.get(objectKey);
passer.remove(objectKey) //if I don't need the
object reference
anymore
...
}
...
}
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[EMAIL PROTECTED]
Announcing the new M5 SDK!
http://android-developers.blogspot.com/2008/02/android-sdk-m5-rc14-now-available.html
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en
-~----------~----~----~----~------~----~------~--~---