Android – invoking active methods from fragments
I'm dealing with fragments. I have an activity and different fragments. Each fragment needs to access a class (called x) that allows it to access the database. However, because I have many fragments, I don't want to create a different class X instance in each fragment. I think it needs a lot of memory. What should I do? I wrote something like this (with getter), but it doesn't work!
public class MyActivity {
  private ClassX classx;
  .....
  public ClassX getClassX() {
     return classx;
  }   
  .....
}
But how can I call it from a clip?
resolvent:
It's a bit like Java problems and Android
If you are accessing a database, see creating a database singleton
So it's similar to:
public class Database {
    // This starts off null
    private static Database mInstance;
    /**
     * Singleton method, will return the same object each time.
     */
    public static final Database getInstance() {
        // First time this method is called by Database.getInstance() from anywhere
        // in your App. It will create this Object once.
        if(mInstance == null) mInstance = new Database();
        // Returns the created object from a statically assigned field so its never
        // destroyed until you do it manually.
        return mInstance;
    }
    //Private constructor to stop you from creating this object by accident
    private Database(){
      //Init db object
    }
}
Then, from your snippets and activities, you can put the following fields in your class (better use basic activities and snippets to save duplicate code)
public abstract class BaseFragment extends Fragment {
    protected final Database mDatabase = Database.getInstance();
}
Then your specific fragment can extend your basefragment. For example, searchlistfragment extends basefragment
I hope this will help
Singletons and databases are worth reading
Hello, Chris
