Would someone please provide me an example of the following Activity/Service/Application combination. I have all three, but I've turned my app into such a mess trying to pass a bunch of variables around the place, and now I don't know what's going on. Please be aware that I am new to android, and I have recently struggled with this, as there are so many ways this can be implemented.
I'd just like to see the 3 classes of activity, service and application where the following happens:
Activity stores variable x in Application, launches Service, and starts Activity 2.
Service retrieves variable x from Application.
Activity 2 retrieves variable x from Application.
Note that variable x could be anything from an Int to an ArrayList, and that in my actual program, there are a lot of variables (hence the desire for an application class).
I'd really appreciate a good example of this specific example, as I've been trying to figure all this out for a while. If someone would please take the time to put together a solid answer, I would greatly appreciate it.
For anyone asking why, the whole thing is a music player. The user picks a song, and the artist/album etc is (hopefully) stored in the application. Then the service is started, which controls the song playback, getting the songpath from the application. The second activity displays a UI with the song information (also from the application) and has next/previous buttons, which will change the value of some of the variables in the application, and instruct the service to retrieve the new values. If the user navigates away, the variables will always exist in the application, so if another UI is created, the song information can be set easily.
Am I using the right approach?
I can provide an example of what I've got, but it is a mess at the moment. Anyhow, just request for that below if you think it will help you to help me.
You don't need to extend
Application
for this. You can just use static member variables in some class, like this:I'd just use sharedpreferences tbh. Sounds like what you need... Make a class static accessible, and then make static getter and setter methods.
http://developer.android.com/resources/faq/framework.html#3
can put a A HashMap of WeakReferences to Objects in Application file and set the value in it...
now you can get the access to Application from Activity well as from service.... using ((YOUR_APPLICATION_NFILE_NAME)this.getApplication()). getter/setter;
Use below Snippets :
Application Class :
Store and Retrieve Value in Activity :
Your Manifest should be like :
Concept for store and get back value from Application is very Simple :
cacheManager.setMerchant("Hello");
cacheManager.getMerchant();
For further reference check this Link Application Class.