-2

I have a Java class say J.java

//j.java
class J
{


}

and I have 2 activity say A1,A2. In A1 I created a object of class J.

A1
{
  J obj = new J();
}

Question- I want to access the same object(obj) in A2.

A2
{
   obj // how can I access this object here? this is created in A1.
}
T_V
  • 17,440
  • 6
  • 36
  • 48
  • 1
    Couple of options. 1. Make the class J as a static class or you can use singleton pattern. 2. Wrap it in an intent or bundle and then send it to other activity. – Sunil Mishra Aug 13 '13 at 05:54

3 Answers3

1

Implement Parcelable for that object. And send that object from A1 to A2 into intent extra.

Parcel data to pass between Activities using Parcelable classes is a very good example to implement Parcelable.

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
1

one way to have a single instance of J across the activities is to have a singleton for the J object.

one way of doing this is having an instance in the application level (have a J instance in a class that extends Application.

the other way is doing this:

class J {
    private static J instance = null;

    private J() {
    }

    public static J get() {
        return instance;
    }
}
thepoosh
  • 12,497
  • 15
  • 73
  • 132
0

You can create an Base or Parent activity. Initialize your object in base activity and extend your all classes from base or application activity.

Muhammad Aamir Ali
  • 20,419
  • 10
  • 66
  • 57