I need to pass a custom object from an activity of one application to the main activity of another.
Will I be able to accomplish this using intent.putExtra as shown:
putExtra("key",obj);
It was showing error since putExtra method does not support this. How can this be achieved?
Any help is appreciated.
EDIT
The following class' instance, I need to pass to another application. I would have the object 'obj' as follows, which I need to pass:
CounterAndNotifier obj = new CounterAndNotifier(5, this)
obj is the object to be passed
public class CounterAndNotifier
{
private int counter = 0;
private int count;
private Runnable runnable;
public CounterAndNotifier(int count, Runnable runnable)
{
this.count = count;
this.runnable = runnable;
}
public synchronized void incrementCounter()
{
counter++;
if (counter == count) {
runnable.run();
}
}
}
Update 2: Example constructor:
CounterAndNotifier counter = new CounterAndNotifier(0, new SerializableRunnable() {
@Override
public void run() {
}
});
or
SerializableRunnable runnable = new SerializableRunnable() {
@Override
public void run() {
/* Running code here */
}
});
CounterAndNotifier counter = new CounterAndNotifier(0, runnable);
Update: Runnable is an interface and isn't Serializable by itself. To get around this, create a new class like this:
public abstract class SerializableRunnable implements Runnable, Serializable {
/* Nothing needs to go here */
}
Then change your references of Runnable to SerializableRunnable and you should be able to serialize your object into an intent without a problem.
Your new object would look like this:
public class CounterAndNotifier implements Serializable
{
private int counter = 0;
private int count;
private SerializableRunnable runnable;
public CounterAndNotifier(int count, SerializableRunnable runnable)
{
this.count = count;
this.runnable = runnable;
}
public synchronized void incrementCounter()
{
counter++;
if (counter == count) {
runnable.run();
}
}
}
You can still create your Runnable objects the same way, just with a different name.
Original Answer:
You can't put a regular object into an Intent
extra. If your object members are all serializable types then you can just implement the Serializable
interface and then you can put the object into the Intent
. Otherwise you can implement Parceable
and flatten your object into a Parcel.
Using Serializable
requires much less code changes so long as your object members are basic types. Also, you should check was is supported by the receiving application first to determine which you should use.
It'd look something like this:
public class YourObject implements Serializable {
private static final long serialVersionUID = -6242440735315628245L;
/* Your class members */
}
Adding to the intent:
Intent intent = new Intent();
intent.putExtra("YourKey", new YourObject());
Getting out of the intent:
YourObject obj = (YourObject)intent.getSerializableExtra("YourKey");