Developing for Android, Part V
Publishing your apps
No code in this tutorial… and this is actually the last in the series. But never fear! I’ll be writing more tutorials, I’ve simply written these 5 to get you familiarised with android. Hopefully, you’re feeling quite confident on some of the aspects now, and you could well be on your way to developing the next killer app!
With that said, I’m going to explain how you can publish your app. It’s a simple process, but you also have to sign your apk before you can publish it to the market.
First off, we need to create a keystore. To do this, you’ll need the JDK installed. Open up a command prompt, and change to whereever you want to save the keystore. Then, type the following:
keytool -genkey -v -keystore mykeystore.keystore -alias my_alias -keyalg RSA -validity 10000
NOTES:
- Replace mykeystore.keystore with whatever_you_want_to_call_it.keystore
- Replace my_alias with whatever alias you want to use (example, android)
Also, if you get this error:
'keytool' is not recognised as an internal or external command, operable program or batch file.
You may want to set the PATH variable. You can do it in the computer properties, but since this isn’t exactly a windows tutorial, I won’t go into that much detail. Instead, let’s do this:
PATH="C:\Program Files\Java\jdk1.6.0_14\bin"
then try the first command again.
NOTE: Replace the path with the path of wherever you installed Java. (Typically you’ll find it in C:\Program Files\Java\jdk%.%.%_%%\bin)
ANOTHER NOTE: This is of course a windows path. Depending on your operating system, this may vary.
After executing the keytool command, it will ask you for various details. Simply enter the values, and it will create your keystore. Make sure you take note of your alias and password, it will ask you for it every time you come to sign an app!
For reference, the questions it will ask are:
- Enter keystore password:
- Re-enter new password:
- What is your first and last name?
- What is the name of your organisational unit?
- What is the name of your organisation?
- What is the name of your City or Locality?
- What is the name of your State or Province?
- What is the two-letter country code for this unit?
You now have your keystore. When you want to sign an apk, you will need to use the following command:
jarsigner -verbose -keystore "/path/to/mykeystore.keystore" "/path/to/myapk.apk" my_alias
Enter your password, and you will see some output similar to this:
adding: META-INF/ALIAS_NA.SF
adding: META-INF/ALIAS_NA.RSA
signing: res/drawable/icon.png
signing: res/layout/main.xml
signing: AndroidManifest.xml
signing: resources.arsc
signing: classes.dex
Your apk file is now signed! (Note that you need to sign it every time before uploading, since building will reset it)
Publishing your app
The next step is of course publishing your newly signed apk file to the android market. Simply navigate your web browser to the market home and follow the steps to register as a developer. If you want to register to sell your apps, you will also need to go through an additional process to become a “registered seller”.
Once you’ve registered and logged in, you’ll reach the page which displays all your registered apps. Of course, if you’re following this tutorial, you probably don’t yet have any, so you won’t have a list of apps to see. :)
NOTE: This page uses a hell of a lot of javascript. Make sure it’s turned on.
When you’re ready, click on “Upload Application”. You will then be presented with a form where you can upload the apk and a maximum of two screenshots, a promotional graphic, and fill in various details such as the title, description and price.
As soon as you click publish, your application will be on the market — there’s no approval system like the iPhone’s app store, so as soon as you search in the market, you should see your app.
You are now officially a dev. Make me proud. :’)
Developing for Android, Part IV
Databases and Menus
Two for the price of one in this tutorial, actually. We’re going to learn about SQLite databases and menus. I’m hoping you’ll at least be slightly familiar with databases already, though SQLite is really quite simple. You can pick up the basics, of which we’ll be using in this tutorial, at the following links:
It may look a little intimidating, but once you get to grips with it, it’s actually quite close to English. :)
Let’s get to it. As usual, we’re creating a package:
package dreamincode.tutorials.dic_tut4;
…and we’ll import the usual suspects.
import android.app.Activity; import android.os.Bundle;
Now there’s quite a lot that we’re going to import that hasn’t already been covered, but do not panic. I’ll explain it all as we go along, and it’s honestly nothing to worry about. First up, a ListView. This is just another widget, and it’s… well, it’s a list. :)
import android.widget.ListView;
Next, we’ll import the stuff related to the menu. We’ll be using a Menu, and a couple of MenuItems.
import android.view.Menu; import android.view.MenuItem;
The next bits are related to the database. The first is self-explanatory, it’s a database. The second is a Cursor. A cursor is a way we can store temporary results from a table in memory. (We select stuff into it, explained a little later… keep reading!)
import android.database.sqlite.SQLiteDatabase; import android.database.Cursor;
And finally, we’re going to import an ArrayList to add our results into, and an ArrayAdapter to basically plug our ArrayList into the list. Again, this will be explained later, at this point all we really have is an overview.
import android.widget.ArrayAdapter; import java.util.ArrayList;
On to the main part of the code, now. :) First off, we’ll open up our class and add a few variables. We’ll have a ListView, an SQLiteDatabase, and a few ints for the IDs of our menu items.
public class dic_tut4 extends Activity { ListView list; SQLiteDatabase db; private static final int MENU_ADD = Menu.FIRST; private static final int MENU_QUIT = Menu.FIRST + 1;
You’ll see why we use these a little later. :)
This is where it gets a little different. I’ll give you one method at a time, and talk through each line.
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.list = new ListView(this); setContentView(this.list); this.db = this.openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null); this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); this.update_list(); }
So, the start is nothing new. Nothing to worry about here. Then we initialise the list. Nothing new here, either. It’s exactly the same as when we created a dynamic layout in part 3. Then we do some new things with our database. First we use openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null);
– this creates a database if it doesn’t exist, or opens it if it does.
– parameter 1 is the name of the database we’re looking to create/open.
– parameter 2 is the mode, doesn’t require much explanation at this point. (Don’t want to give you an information overload) :)
– parameter 3, you don’t even need to worry about. If you’re interested, do some digging on CursorFactory.
Then another new line: this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)");
– this will create a table if it doesn’t already exist
– it will add a single field into the table, called value. It is of type REAL, which is just like a double in Java.
And finally, this.update_list(); … this is actually a custom method we’ll be writing to query the database and populate the list. More info later, for now let’s focus on the menu.
Creating a menu
Simple stuff actually. We use onCreateOptionsMenu(), which is called when the user hits the menu button.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, "Add").setIcon(android.R.drawable.ic_menu_add);
menu.add(0, MENU_QUIT, 0, "Quit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return super.onCreateOptionsMenu(menu);
}We’re simply adding 2 items: “Add”, and “Quit”. We also set the icons for them using some default android resources. If you want a full list, this site is pretty cool.
The next method we’ll be using is onOptionsItemSelected(), which is called when the user selects an item in the menu. We use the IDs we assigned in onCreateOptionsMenu() MENU_ADD and MENU_QUIT to decide what to do.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case MENU_ADD:
db.execSQL("INSERT INTO table_of_dics(value) VALUES(" + String.valueOf(Math.random()) + ")");
this.update_list();
break;
case MENU_QUIT:
this.db.close();
this.finish();
}
return super.onOptionsItemSelected(item);
}So, we’re using a switch() to find the ID of the menu item which called this method. If it’s add, we’re going to perform some SQL and insert a random value into the table. Then we’ll update the list, just like we did in onCreate(). (Remember, we’re defining this method ourselves later)
If the user selected the “Quit” option, we’ll simple close the database and finish the activity. :)
NOTE: The SQL used here, INSERT INTO will insert a random value into the table. Remember to refer to the links at the beginning if you get stuck on the SQL.
Lastly, we’re going to define our method for updating the list. It’s quite simple, but the code is quite different to what we’ve done so far. If you’ve ever done any database work through software/web before, you may notice a few similarities here. We basically execute the query. Then loop through each row in the result, adding it into an ArrayList. Lastly, we set the adapter for the list to display the arraylist we created. The code looks a tad complex, but it’s really quite simple:
private void update_list() { ArrayList<string> db_results = new ArrayList><String>(); Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); while(cursor.moveToNext()) { db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value")))); } cursor.close(); this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results)); }
I’ll break this one up:
ArrayList — create an ArrayList, where we’ll store the results to display in the list.
Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); — create a cursor based on the query (this select statement will return all the values stored in the table, and order them)
while(cursor.moveToNext()) { — while there is still something in the cursor to read (while we still have another row to read)
db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value")))); — add the value from the row into the arraylist we created.
} — this is self explanatory, really. :)
cursor.close(); — close the cursor: we’re done with it now. We have all our results in the ArrayList, which we can now set as the adapter:
this.list.setAdapter(new ArrayAdapter — set the adapter.
- parameter 1: the activity we want it for
- parameter 2: the layout type (we can add multiple widgets to a list item, but simple_list_item_1 is a default in android: simply a single TextView.
- parameter 3: the arraylist which we created and populated earlier.
And that’s it! Don’t forget to close off your class
}Complete code:
package dreamincode.tutorials.dic_tut4; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.view.Menu; import android.view.MenuItem; import android.database.sqlite.SQLiteDatabase; import android.database.Cursor; import android.widget.ArrayAdapter; import java.util.ArrayList; public class dic_tut4 extends Activity { ListView list; SQLiteDatabase db; private static final int MENU_ADD = Menu.FIRST; private static final int MENU_QUIT = Menu.FIRST + 1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.list = new ListView(this); this.registerForContextMenu(this.list); this.db = this.openOrCreateDatabase("dic_tut5", MODE_PRIVATE, null); this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); this.update_list(); setContentView(this.list); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ADD, 0, "Add").setIcon(android.R.drawable.ic_menu_add); menu.add(0, MENU_QUIT, 0, "Quit").setIcon(android.R.drawable.ic_menu_close_clear_cancel); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_ADD: db.execSQL("INSERT INTO table_of_dics(value) VALUES(" + String.valueOf(Math.random()) + ")"); this.update_list(); break; case MENU_QUIT: this.db.close(); this.finish(); } return super.onOptionsItemSelected(item); } private void update_list() { ArrayList<String> db_results = new ArrayList<String>(); Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); while(cursor.moveToNext()) { db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value")))); } cursor.close(); this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results)); } }
Developing for Android, Part III
Dynamic Layouts in Android
No XML in this tutorial! We’ll be completely designing our application in Java, and creating our layout completely dynamically. The benefits of this are that we can add an undefined amount of widgets at run time. This is a pretty useful skill, but not brilliantly documented. (Everything is ZOMG LAYOUT.XML FTW!!1!)
Okay, so let’s get started. We won’t be touching on events in this tutorial, our app won’t actually do anything, per se… it’s merely an example of adding stuff dynamically. You’ll notice how we set the properties through Java, quite similarly to how we define them in the XML.
To start off, remember we’re creating a package, as usual.
package dreamincode.tutorials.dic_tut3;
Next, we’re going to import the usual suspects… Activity and Bundle.
import android.app.Activity; import android.os.Bundle;
The next two are new. One you may recognise from our layouts before… LinearLayout. We’re also going to use a ScrollView. The reason we’ll be using a ScrollView is that we’re going to add a hell of a lot of widgets, and they wouldn’t all fit on screen. If we don’t put our LinearLayout inside a ScrollView, it simply won’t scroll and the user won’t be able to reach all the widgets!
import android.widget.ScrollView; import android.widget.LinearLayout;
The last things we need to import are our widgets. We’ll be using an EditText, a TextView, a Button and a CheckBox. We’ve already seen the first three in parts 1 and 2 of this tutorial, but the CheckBox is new. (And I hope the name is self-explanatory for what it is!) ;)
import android.widget.Button; import android.widget.TextView; import android.widget.EditText; import android.widget.CheckBox;
Now it’s time to get on with our code. We’re only going to extend Activity this time, remember we won’t be using events. This bit’s nothing new, so I’ll just throw in the opening of the class and the opening of the onCreate() method. (Note, if you’re not familiar with this, check part 1 and part 2)
public class dic_tut3 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Time to get dirty. Dynamic layouts aren’t always the most elegant of solutions, but they can be fun, and sometimes easier to implement. They’re also really useful for certain occasions (such as SmartCalc, my app: it uses a dynamic layout to decide how many textboxes are needed at runtime)
Code first, explanation afterwards.
ScrollView sv = new ScrollView(this); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll);
LINE 1: Creates a ScrollView object, which is a part of this Activity.
LINE 2: Creates a LinearLayout object, which you hopefully remember from the layout.xml we discussed before.
LINE 3: Sets the orientation of our LinearLayout. Remember how we used android:orientation="vertical" before? Same principal applies here.
LINE 4: Adds the LinearLayout to the ScrollView. Remember, we want to be able to Scroll the LinearLayout View.
NOTE: A ScrollView can **only** have one view added to it. If you try to add more than one, your application WILL force close. If you need to reset it, use ScrollView.removeAllViews(); and re-add whatever you need. (This is why we’re going to add all our widgets to the LinearLayout as opposed to the ScrollView!)
Adding widgets dynamically
Actually, this same principal applies to all our widgets. But I’ll use a few, just to demonstrate. :) This one should look relatively familiar, since we played with TextView.setText() in part 2.
TextView tv = new TextView(this); tv.setText("Dynamic layouts ftw!"); ll.addView(tv);
Notice how we use addView() on ll, our LinearLayout, just like we added ll to sv? That’s all it takes! :)
Now, let’s do a Button and a EditText. Same principal, just like I said:
EditText et = new EditText(this); et.setText("weeeeeeeeeee~!"); ll.addView(et); Button b = new Button(this); b.setText("I don't do anything, but I was added dynamically. :)"); ll.addView(b);
(Remember, when you run the application, the button won’t actually do anything: We haven’t added an OnClickListener! If you want, you may want to revisit the button at the end of this tutorial and try adding an event by yourself. (Use part 2 of this series as a reference if you get stuck)
The next is still the same principal, but I’ve added it in a loop. 20 pointless CheckBoxes, coming up!
for(int i = 0; i < 20; i++) { CheckBox cb = new CheckBox(this); cb.setText("I'm dynamic!"); ll.addView(cb); }
This is really just to pad out our layout, so we can really see how useful that ScrollView is. :)
The very last thing we need to do is use setContentView() — similar to how we did before. Remember the this.setContentView(R.layout.main);? Pretty much the same, only now we’re going to use the ScrollView we created earlier instead:
this.setContentView(sv);
And lastly, close off the method and class!
} }
Now, if you run this, you'll get a rather crude, but biiiig layout, complete with all the widgets that we added dynamically.
Complete code:
package dreamincode.tutorials.dic_tut3; import android.app.Activity; import android.os.Bundle; import android.widget.ScrollView; import android.widget.LinearLayout; import android.widget.Button; import android.widget.TextView; import android.widget.EditText; import android.widget.CheckBox; public class dic_tut3 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ScrollView sv = new ScrollView(this); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); sv.addView(ll); TextView tv = new TextView(this); tv.setText("Dynamic layouts ftw!"); ll.addView(tv); EditText et = new EditText(this); et.setText("weeeeeeeeeee~!"); ll.addView(et); Button b = new Button(this); b.setText("I don't do anything, but I was added dynamically. :)"); ll.addView(b); for(int i = 0; i < 20; i++) { CheckBox cb = new CheckBox(this); cb.setText("I'm dynamic!"); ll.addView(cb); } this.setContentView(sv); } }
See if you can add an OnClickListener to the button, just have a play about with it until you feel fairly confident... I won't be explaining too much about the layouts in the coming tutorials, more on actual features such as SQLite. :)
Developing for Android, Part II
Again, originally written for </dream.in.code> but I like to add this stuff to my blog as well. :)
Basic Layouts and Events
Now that we got the basics done, it’s time to get into developing our first app. It’s not the most impressive application, but it’s a great starting point.
This will most likely seem very familiar if you’ve learned programming on the console in the past. We’re going to prompt for a name, and display a customised message. However, we’ll have a user interface rather than printing on the console. :)
We’re going to start with the XML. We need a layout which we can program around.
Step 0: Creating the project
So we’re on the same wavelength, let’s use the same project name, package, etc.
Step 1: Putting the UI XML together
I’ll run through this one element at a time. it’s all really simple, and you should recognise a lot of this from part 1.
To start, remember, it’s XML:
< ?xml version="1.0" encoding="utf-8"?>We’re going to use a linear layout, which fills the parent and has a vertical layout (again)
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ></linearlayout>
Next, we’re going to the first TextView. Remember, the TextView is like a “Label”, from .NET. At this point, all we need to do is set the width, height, and set the text. This time, we’re just going to use a static string, rather than linking into the ./res/values/strings.xml file.
<textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter your name:" />
The next thing we need in our LinearLayout is an EditText. This is basically a TextBox.
<edittext android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txt_name" />
Only one new thing here, we give it an ID. We need to give it an ID so that we can reference it in the actual Java application.
android:id=”@+id/txt_name” — I’ll call it txt_name, I like to prefix my widgets so they’re easier to remember and reference later on.
Only two things left now: The Button, and the TextView. Nothing new in either of these now.
<button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/btn_confirm" android:text="Confirm~" /> <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tv_welcome" />
Note that we don’t set the android:text attribute in the final TextView? That’s because we’re going to give it its text when the user presses the “Confirm” button. (btn_confirm)
Lastly, we just need to close off our layout:
Step 2: Bringing it all together in Java
This time we’re going to write our own Java. We’re going to use multiple inheritance (don’t be put off, it’s really very simple) so that we can make our class both an Activity (the main application) and an OnClickListener (to listen for clicks on the button)
First up, remember we’re working on a package:
package dreamincode.tutorials.part_two;
Next, we’re going to import some stuff. The first two are nothing new:
import android.app.Activity; import android.os.Bundle;
Remember we used both of these in part 1.
This is where it gets interesting, though. We’re going to import three widgets.
import android.widget.TextView; import android.widget.EditText; import android.widget.Button;
I won’t explain them… hopefully your memory is good enough to remember that we used these names in the XML layout earlier. :)
The next two will take a little explaining.
import android.view.View; import android.view.View.OnClickListener;
- We import the View because that’s the parameter which our onClick event requires.
- We import the OnClickListener because, well… we want our Activity to be an OnClickListener, too.
This is where the multiple inheritance comes in. We’re calling our class dic_tut2, and it’s going to extend Activity, just like we did in part 1. It’s also going to implement OnClickListener because we’re going to be listening for clicks on the button.
public class dic_tut2 extends Activity implements OnClickListener {
Now it’s time for the onCreate method. Just like we did in part 1, only with a few extra lines (explained afterwards!)
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b = (Button)this.findViewById(R.id.btn_confirm); b.setOnClickListener(this); }
Specifically, the last two lines are the new ones. We’re going to create a Button from R.id.btn_confirm (remember, that’s the ID we used in the XML!) Then we’re simply going to set this as the onClickListener for said button. Simple stuff, eh? :)
NOTE: We need to cast the return value of findViewById() to a Button, by default it will return a View.
The very last thing we need to do is set our onClick method: the one which is called when the user clicks the button (after we set this as the OnClickListener for said button!)
@Override
public void onClick(View v) {
TextView tv = (TextView)this.findViewById(R.id.tv_welcome);
EditText et = (EditText)this.findViewById(R.id.txt_name);
String text = "Hello, " + et.getText().toString() + ".\n\n";
text += "Welcome to android development. :)";
tv.setText(text);
}Note that we use findViewById() again to get the TextView for which we’re going to set the text, and also the EditText which contains the user’s name. Then, all we do is create our string (I hope this is nothing new!) and simply setText() on our TextView which displays the final message.
Don’t forget to close off your class!
}Finally, here’s the complete code. dic_tut2.java:
package dreamincode.tutorials.part_two; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.EditText; import android.widget.Button; import android.view.View; import android.view.View.OnClickListener; public class dic_tut2 extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b = (Button)this.findViewById(R.id.btn_confirm); b.setOnClickListener(this); } @Override public void onClick(View v) { TextView tv = (TextView)this.findViewById(R.id.tv_welcome); EditText et = (EditText)this.findViewById(R.id.txt_name); String text = "Hello, " + et.getText().toString() + ".\n\n"; text += "Welcome to android development. :)"; tv.setText(text); } }
And the layout, main.xml:
< ?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter your name:" /> <edittext android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txt_name" /> <button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/btn_confirm" android:text="Confirm~" /> <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tv_welcome" /> </linearlayout>
Enjoy! :)
Developing for Android, Part I
I originally wrote this tutorial for </dream.in.code>, but I like to get my tutorials around a bit.
Welcome to Android.
We hope you enjoy your stay.
So, first off, a bit of an introduction. This is the first part of (hopefully) many tutorials related to the android platform. In this tutorial, we’re only going to cover the very basics: how to design your application, and how to utilise the XML layouts to design your user interface.
Since this series of tutorials is more directed at the code, I’m not going to cover setup & installation. Instead, here’s a link to get yourself set up with the SDK and an emulator.
Personally, I’ve never really been a huge fan of Java. And when I first tried Android, I wasn’t too keen. But it’s come a long way since it was first released. Once you get into the android SDK, it begins to get really interesting. Plus, the idea of earning a little bit of cash on the side for designing a little app for your phone has quite a nice appeal. :)
The market
The market is awesome. It’s extremely easy to release and update your applications, and I’ll be writing a tutorial all about publishing your apps, how to sign them, how to create a jar keystore, all the fun stuff.
Get started already!!1!one!
Okay. Enough intro, let’s get to some development! :)
…sorry. No programming yet. We’re going to be reading the project template, and I’ll be explaining it line for line. It’s best to take this stuff slow at first, because it’s so different to a lot of “regular” projects. But at least there’s code! :)
Create a project, you can call it anything, but I’m going to be following this structure along the series of tutorials:
layout.xml
The layout.xml is… sorta important. It’s a great way to design your user interfaces, but it’s not always necessary: you can create your interfaces through pure Java, which is personally my preferred method… but it’s still good to know how to use the xml layouts. They help to keep the code for your activity more organised. (Coming from a C++/wxWidgets background, I’m in the habit of creating my programs through pure code, you may prefer the XML process)
Right. Enough rambling. I’ve analysed the ./res/layout/main.xml, and broken it up, line by line.
yep: we just use standard XML to declare the layout:
< ?xml version="1.0" encoding="utf-8"?>We use a LinearLayout to define our layout as being, well… linear:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"Next up, we have some properties:
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"Note the three properties:
android:orientation — which direction the layout is filled. Contrary to what you may think, this isn’t based on the angle of the phone. Using “vertical” simply means “add widget number 2 below widget number 1, add widget number 3 below widget number 2, … add widget number n below widget number n-1″. :)
android:layout_width — the width of the object. We’re going to use “fill_parent” to fill the width of the screen
android:layout_height — the height of the object. We’re going to use “fill_parent” again, to fill the height of the screen.
Lastly, we’re going to close the LinearLayout item. Note we want more items inside the LinearLayout, so we’re just going to use > instead of />
>
Next, we’re going to define a TextView. The TextView is like a Label in .NET, or a wxStaticText in wxWidgets. It basically puts a static piece of text on the screen.
<textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
You’ll notice it’s pretty similar to how we defined the LinearLayout. Differences:
android:layout_height=”wrap_content” — the TextView will be resized according to the text it displays. The longer the string, the taller the View.
android:text=”@string/hello” — the string to display. @string refers to the ./res/values/strings.xml file. (More on this later)
/> — this time, we’re not putting any other items inside it, so we can close it off XML stylee. We could just as easily use
<textview ... ></textview>but it seems a little pointless here. :)
Since that’s all we want in the LinearLayout, we’re going to close our layout off:
strings.xml
This one's much simpler. Put simply, this file contains strings which are built in to the application at compile time. Note the hello string, which we referenced in our TextView in ./res/layout/main.xml
< ?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, dic_tut1!</string> <string name="app_name">dic_tut1</string> </resources>
The Java!
Lastly, we're going to put our layout together in the code. I've commented this bit up, so it's easy for you to understand.
package dreamincode.tutorials.part_one; import android.app.Activity; // Activity: the "main" part of the application import android.os.Bundle; // Bundle: stores a "saved state" for your app to remember how it was when moved to the background public class dic_tut1 extends Activity { // inheriting the Activity class /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { // consider this the "entry point" (main) of your application super.onCreate(savedInstanceState); // call the super to restore the state (does the work for you) setContentView(R.layout.main); // set the main content view to ./res/layout/main.xml } }
That's all for now!
There's obviously more to it than this, things such as the AndroidManifest.xml file, but I'm not going to go into that now. We'll dive into that as and when we need it, it's really rather trivial and honestly nothing to worry about. :)