I have 2 activities, ActivityA and ActivityB, with 3 buttons each. I show ActivityA on one connected device and ActivityB on the other connected device. The buttons can each be in 1 of 2 states but the states need to be reflected on both devices. I’m using a util class with static methods to receive button presses from both activities and send it to the service as well as update the state of the buttons in both activities upon the callback from a service.
Right now, each button calls a function in its corresponding activity from the xml. For example Button1‘s onClick looks like this:
android:onClick="button1Clicked"
That function (from its corresponding activity) calls a function in UtilClass and looks like this:
public void button1Clicked(View view) {
UtilClass.button1Cliked();
}
I set an enum in UtilClass so I know which button to update (in both ActivityA and ActivityB) upon a callback from the service. It looks like this:
public class UtilClass {
public static Button buttonPressed = WfdOperationButton.NONE;
public enum Button {
BUTTON1, BUTTON2, BUTTON3
}
public static void button1Cliked() {
buttonPressed = Button.BUTTON1;
//call asynctask to tell the service button1 was pushed by passing
//buttonPressed
}
public static void button2Cliked() {
buttonPressed = Button.BUTTON2;
//call asynctask to tell the service button2 was pushed by passing
//buttonPressed
}
...
My question is how can I use the same enum from UtilClass in ActivityA and ActivityB to consolidate the 3 buttonXClicked() functions in UtilClass? My attempted change in UtilClass is below:
public static void buttonCliked(Button inButton) {
buttonPressed = inButton;
//call asynctask to tell the service inButton was pushed by passing
//buttonPressed
}
This doesn’t work though because I can’t use a non-static enum in ActivityA or ActivityB in a static function to pass in. But I need the enum to be non-static since I need to use it in the UtilClass.
I’m new to Android so if I’m doing anything else wrong, I’d be grateful if you pointed it out.
Thanks!
These problems with static methods are perhaps evidence of O-O design issues. From a quick read it sounds like you’re trying to do too many things in one class, and it’s getting messy. Some ideas:
Why are you defining your
Buttonenum as a nested class here? You could just externalise it (i.e. move to its own file) and then the sharing problem goes away, assuming I understood you here.In general, if you are writing a helper class like
UtilClass(though I doubt it’s actually necessary here), consider making everything non-static.To store state properly, consider one of the recommended Android methods. For simple things like this, Shared Preferences might be enough. If you really don’t want to do that, a stateful singleton object which references the enums as appropriate should do it. Then your call would look something like:
and
or similar.