Android - 2 (Eclipse project)

Now that I understand some of the basics of Android development, I will start exploring more into the Android and Eclipse project and get a better idea about what the files in this project mean. Then I will try to create a simple app to sort of gel all the ideas together. Lets get started -
Android Project - The android project consists of the following folders and files 
  • src - contains your code packages (namespaces) and code files
  • gen - contains the files generated by Eclipse
  • res - contains the resources files
  • Android Manifest - contains the configuration settings for the project
Activity - An activity is a single focussed thing that a user can do. Since most of the activities interact with the user, Activity class creates a window in which we can place our UI components. The following diagram shows the life cycle of an activity. This diagram is taken from developer.android.com.

Sample Application - We will try to build a simple app in Android which will allow us to insert some text in a textbox and on click of a button will log the text in the debug logger. We will also create a help button, which will allow us to go to a different activity.
So, first up, I create a MainActivity and add a EditText and a button to the UI. Then in my MainActivity.java file in the onCreate of MainActivity, I write the following code -

Here, in the MainActivity class I create an OnClickListener variable that takes care of the click event. Here, unlike .NET, we can not get the text value by doing something like EditText.Text. There are no such properties, so we have to use the findViewById method to find the view and then use its getText() method to get the text. Log.d takes a tag and a message.
Now to create another view, we use the New-Class feature to create HelpActivity.java. In the onCreate for this Activity, we create a TextView on the fly and set some Text into that as shown below -

This creates the view, but we haven't hooked it up with the MainActivity yet. So, I create a Help button in the UI and add an OnClickListener to it in the MainActivity.java file. In the listener, we create a new Intent and then start the activity. An Intent is a way in android to suggest some kind of action or something that we want to do. In this case, we are telling Android to 
We also need to hookup this HelpActivity in the Android Manifest file as well as shown below -

When you run the app, you see the following -

After clicking the button, you can navigate to the DDMS perspective in Eclipse and in the LogCat window, you can see the text logged as shown below.

After clicking the help button, you can see that the app navigates to a different view.
If you are wondering, why this app is called Calculator, thats because I plan to create a simple Calculator app but just for starters, I created this app.

No comments: