I have written a rather small App with only one activity. From my understanding an activity has to be seen as kind of a view and controller in one class.

But even for a little app, with 3 dialogs (made with AlertDialogBuilder and all those anonymous inner classes that come with it) my activity has 500+ LOC and became very hard to maintain. The activity houses mainly android lifecycle handlers and view handling. Business logic is very little.

How to handle activity classes to keep them readable and maintainable?


When I develop for Android, I always think of my Activities as my controllers and my layouts (XML) as my views. The layouts interact with each other and the business logic through my Activities (controllers). Here are some mistakes I learned a lot from:

  • Keep your component Listeners as separate classes. I used to keep them as inner classes to my components (mainly Buttons). This made my Activity code a pure mess and editing it was like hell.
  • Try and have separate Activities for every action you have. This will make your code easier to get back to if you need to change stuff (and thus more maintainable)
  • If the listeners are separate classes I do not have access to the activities members, how do you handle this? Usually you would need access to those members from e.g. a click handler.
    – metacircle
    Apr 20 '13 at 5:30

Below are the points you need to remember:

  • Always bifurcate your codes in different methods. I mean for example, if you are registering the various event listeners then make one method "registerListeners()"

    public void registerListeners() {
         // your button, listview....components event listeners codes

    then in onCreate(), call this method. By doing this, you have all registered listener codes at one place and they more readable and searchable.

  • getting all controls ID will be in another method named "initControls"

    public void initControls() {
         // etc..etc...components

    then in onCreate(), call this method. By doing this, you will have all controls id at one place and it will look very neat and clean. you can search it very easily.

    onCreate() {
         //after setcontentview

Hope, this helps you to explore more on code writing. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.