Reputation: 4147
I'm working on an Android application and am faced with a refactoring issue; most of my activities need certain notification abilities, i.e. showing a Toast message. This is handled by a superclass which extends Activity
Activity
-NotificationActivity
--MyActivityA
--MyActivityB
and so on. I then decided to refactor two of my activities which make use of a Spinner which is populated by a database cursor. The hierarchy now looks like this:
Activity
-MyNotificationActivity
--MyActivityA
--MyActivityB
--MySpinnerActivity (sets up Spinner and Cursor)
---MySpinnerActivityA
---MySpinnerActivityB
The problem I am facing now is this - I am writing a new Activity class which will also make use of a database Cursor but to populate a ListView. I would like to extend ListView to make use of built in Android List management, but I also need access to the Cursor set up methods and Notification methods, which already exist in my class hierarchy.
I'm really keen to avoid code dupication. Any suggestions?
Cheers, Barry
Upvotes: 1
Views: 137
Reputation: 1577
In dealing with a similar issue (a bunch of activities which show ProgressDialogs), I avoided extending a superclass with the ProgressDialog functionality.
Instead, I wrote a separate class, "LoadingDialog", to handle it. In each Activity that needed this functionality, it would have an instance of class LoadingDialog as a field. And, for any Context- or Activity-dependent functionality, the Activity could pass a reference to itself, or expose other bits of itself as needed.
In your case, perhaps you could write some kind of "ToasterFunctionClass" which encapsulates the common functionality, and have an instance of it in each of the appropriate Activities.
public class ListStuff extends ListActivity {
private ToastFunctionClass toaster = new ToastFunctionClass(this); //pass yourself so that toaster has a Context in which to do UI stuff.
onSomethingHappened() {
toaster.showToast("Something happened");
}
}
Upvotes: 1