0

I am trying to build my first android app. I have multiple Activities and I am using a Handler and an AssetFileDescriptor in order to play a sound file.

My problem is, how can I pass these objects around? I have one Activity that starts a timer via the handler, and another which stops the timer via the handler. Should I pass these objects around between Activities, or is there another way?

I am not used to Java, but I was wondering if I could make a config static class or something that creates all of these objects, and then each one of my Activities would just access these objects from this static config class. However, this has its own problems, since in order to call the method getAssets(), I cannot use a static class ("Cannot make a static reference to a non-static method.")

Any ideas?

fusilli.jerry89
  • 309
  • 3
  • 11
  • If it's state that needs to stay around across multiple activities, it sounds like you should be using a `Service` to handle the timer. – Kevin Coppock May 09 '14 at 22:31

1 Answers1

0

This simplest solution would be to store objects in the Application class, here is a SO answer on the topic Using the Android Application class to persist data

Another more advanced option would be to use Dagger. It is a Dependency Injection framework that can do a lot of cool stuff but is somewhat difficult to get running (atleast took me some time to get working).

Dagger enables defining a Singleton class like this:

@Singleton
public class MySingletonObject {

    @Inject
    MySingletonObject() {
        ...
    }
}

And whenever you need it in your app:

public class SomeActivityOrFragment {

    @Inject MySingletonObject mySingletonObject;
    ...
    mySingletonObject.start();
}

public class SomeOtherActivityOrFragment {

    @Inject MySingletonObject mySingletonObject;

    ...
    mySingletonObject.stop();

}
Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33