Monday, June 11, 2012

How to Become a Better Android Programmer

So you've come here to learn a thing or two about Android programming eh? Or maybe you are just learning and want to start in the right direction. Either way, this is for you.


When I started developing Android applications, I was just out of high school. As such, I wrote high school level programs. They worked, but software-wise, they were horrible. Duplicate code, single classes doing all the work, etc... But I learned.

Model View Controller Pattern
This. When you move on from here and continue googling random search terms, Google this. Model View Controller Pattern or MVC for short. It is a pattern focused around UI's that is perfect for mobile development and should be used by every Android programmer, all the time. This pattern focuses on three different elements per screen in your app. The model, the view, and the controller. These three different, separable, and reusable classes talk to each other in a very specific way.

The Model is like the data you are going to present. Say you are writing a contact book app; the model, in this case, would be all the data containing the contacts and their information.

The View is the screen your user will see and interact with. This will be the class that renders the xml view and handles all UI interactions.

The Controller is the class that controls the interaction between the view and the model. The view will ask for a list of contacts and the controller will grab the contacts it has, and give them to the view.

Now these interactions are very important. A controller can talk to the model and the view. Views and models interact with the controller at a very high level. In reality, a model should know nothing about the controller (or the view for that matter) because it is just the data and nothing else. And the view should not be manipulating the models, it should just be consuming them. The controller manipulates/creates/destroys the models for the view. It is important to note that the View does not own the Model, the Controller does.

public class Model{
   private String someData;
}

public class Controller{
   public List data;

   public List getData() {
      return data;
   }
}

public class View extends Activity{
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Controller controller = new Controller();
        controller.getData();
    }
}

No comments:

Post a Comment