Call Activity Method From Fragment

android, android-activity, call, fragment, methods

Solution

This is a little bit more of a Java question and android.

If you looking at accessing the database, look at creating a database singleton.

So something like:

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
    }

}

So then from your fragments and activities you can then place the following field in your class's (Better use use a base activity and fragment to save you repeating code).

public abstract class BaseFragment extends Fragment {

    protected final Database mDatabase = Database.getInstance();

}

Then your concrete fragments can extend your `BaseFragment` e.g. `SearchListFragment extends BaseFragment`

Hope this helps.

Worth reading about singletons and database

Regards, Chris

Problem

I'm dealing with fragments. I have an `Activity` and different `fragments`. Each `fragment` need the access to a `Class(call it X)` that allow it to access a database, but, because I have a lot of fragments, I don't want to create a different instance of the `Class X` in every fragment as I think it will require lots of `memory`. So how can I do? I wrote something like this (with a getter), but it doesn't work! ``` public class MyActivity { private ClassX classx; ..... public ClassX getClassX() { return classx; } ..... } ``` But than, how can I call it from the `fragment`?

Original source