user2144406
user2144406

Reputation: 310

Android multiple activities access one java class

I am new to android development and appreciate any help. I have multiple android activities that have to access one java class. This class has synchronized getters and setters, but I'm having problems making a single instance of this class across the activities. Is there any way to easily do this?

Upvotes: 1

Views: 4031

Answers (2)

kamituel
kamituel

Reputation: 35970

What you need is a 'singleton' pattern:

public final class Singleton {
    private final static Singleton ourInstance = new Singleton();
    public static Singleton getInstance() {
        return ourInstance;
    }

    // Contructor is private, so it won't be possible 
    // to create instance of this class from outside of it.
    private Singleton() {
    }
}

Now in your child classes, just use:

Singleton.getInstance()

to access one, single object of this class.

Upvotes: 2

codeMan
codeMan

Reputation: 5758

you can use singleton design pattern. Here is one way of implementing it in java

public class Singleton 
{
  private static Singleton uniqInstance;

  private Singleton() 
  {
  }

  public static synchronized Singleton getInstance() 
  {
    if (uniqInstance == null) {
      uniqInstance = new Singleton();
    }
  return uniqInstance;
  } 
 // other useful methods here
} 

Upvotes: 0

Related Questions