Android Application Development Guide

advertisement
My First Android Application
Overview:
1.
2.
3.
4.
5.
6.
Eclipse Breakdown
Activity Breakdown
XML Files
Debugging Options
Incorporating Databases
Sample Code/Output
Additional Resources
(1) Eclipse Breakdown
Eclipse is a cross-platform IDE (Integrated Development Environment) for Java
programming. It supports Android development by extension (Android programs also being
written in Java). Android development through Eclipse requires certain plugins/features to
be installed and modified however, so don’t expect to begin developing right after installing
Eclipse.
The basic “workspace” can be seen in the following, with key features circled/numbered for
your convenience, and explained more thoroughly below:
2
1
3
4
1) As you can see, the current, working project is DatabaseTest. The project folder is
expanded, showing all relevant folders and files of the project. Some important files to
note:
a) src/package_name/ : contains all classes, activities,
and other object oriented features of the application.
In the above example, the only activity class is the
DatabaseGUI.java file.
b) gen/package_name/ : contains R.java, an
automatically-updated java file which contains
information about the application. It is strongly
discouraged to edit or touch this file in any way.
c) Library or platform : contains all necessary .jar files for
compilation. In most Android applications, this will
contain “android.jar”, and “usb.jar” and “maps.jar” if
the platform is the Google API version.
d) assets/ : contains application-private files for internal
use by the application.
e) res/ : contains drawable folders which hold all nonsystem images used by the application. In addition, it
contains the layout folder, which holds all .xml layout
files for the application (see section 3 for more
information). Finally contains the values folder, which
contains strings.xml, an xml file designated for storing
basic string values (application name, activity names,
etc.). Also sometimes contains a “raw” folder, which
functions similarly to the assets directory in storing
application-private files.
2) This tabbed portion contains all open files of the application. Try not to open unnecessary
files, as it can become cluttered very quickly.
3) This window usually contains a host of useful windows pertinent to the current perspective.
Since the current perspective is “Java”, the default tabs are:
a) Console : used in Android development to update status of emulator/device activity,
such as the launching of activities.
b) LogCat : a very useful debugging tool for Android development; functions similar to the
Console window for regular Java development by becoming a useful output screen for
any text-printing statements.
4) Perspectives are a very important feature of Eclipse. If you’ve ever worked with Eclipse
before, you know about the Java/Debug perspectives, which allow programming in a
normal environment and access specific debugging information respectively. An Android-
specific perspective however is the DDMS, whose default windows allow you to interact
with Android-based devices (emulated or not) very easily. By default it contains “Devices”
and “File Explorer” tabs, in addition to the normal “Console” and “LogCat” frames usually
included in the Java perspective.
a) Devices : Used to monitor the status of Android devices.
b) File Explorer : Used primarily to push/pull files from an Android device. Can also be used
to delete files, move files, and perform other formatting tasks.
(2) Activity Breakdown
An activity is basically the same as a java application class. Represented as code, every basic
activity will have the same basic features:
Line 1: Package declaration – a necessary line which declares what package this class is a
member of.
Line 3-8: Import statements – define any library resources which the class depends on. Eclipse
actually has a built-in automatic-import hotkey (Ctrl-Shift-O). Using this will tell Eclipse to
automatically generate any import statements not already declared and necessary for the
program’s execution. This is a very useful tool.
Line 10: Extension – Make sure to extend your class as an activity! Obviously not all of your
classes are going to be Activity classes, but those that are must extend Activity.
Line 13: onCreate method – this method is called when the Activity is first created, and must be
implemented by every Activity class. This class will perform any tasks that the class must
perform prior to user interaction.
Line 14: Calls the parent onCreate method – another necessary line in the file. Also, this must
be the first line in the onCreate method!
Line 15: Sets the content view – this line basically assigns a certain XML file to act as a GUI
screen for this Activity. In this case, the XML file “main.xml” is used.
(3) XML Files
XML files are the primary tools for GUI design in Android development. Although it is not
necessary to use then to develop a GUI for your application, it is highly recommended.
Designing the user interface in an XML file allows programmers to visually see every change
they enact, and format things very easily. It also allows them to revise and change the GUI
separate from the .java files/classes, allowing for overall better flexibility and code
readability/reliability.
XML files can be edited in two ways: graphically, and with raw code. The following is an
example of the graphic design of the xml file:
XML files can also be edited by changing the raw code, but this is much messier and not
recommended for those who do not have extensive experience with XML programming. Here’s
an example of the code of a very basic xml file:
While it would be possible to give you some basic GUI design tips, the best way to learn how to create
the GUI portion of an application is to design it yourself. Experiment with different layouts, forms, and
widgets, and find what works best for you.
(4) Debugging Options
LogCat:
One of the quickest debugging methods, this involves outputting certain values to the LogCat
pane. This can help check values of important variables at specific times in the program. The
only requirements for using this are to import the proper LogCat packages, and use correct
syntax.
Debug mode:
Using TextViews to debug: This method is useful if you want to keep track of certain
numbers/values in the GUI of the application itself, rather than having to check values in
Eclipse. The process involves continual updating of the TextView by way of the setText()
method (perhaps on a button click, or other event).
Some helpful tips:
I know this is common advice, but if your application just won’t seem to work (random
crashing on starting, etc.), try restarting Eclipse. Try restarting the emulator. Maybe even your
computer. If a certain Activity won’t load properly, you might try cutting and pasting the code
back into the file. I can’t tell you how many hours can be wasted looking through code, only to
restart something and have the application magically begin working again.
If your emulator is slow or takes a long time to boot up, don’t worry! There’s not much
you can do to expedite the process, so you might as well just use the time productively. Even
once the emulator is up and running, it can be very sluggish, and you might have latency issues
that don’t exist on a real device.
Test your application on the device you intend to run it on if possible. This does not
mean an emulated version, but the real thing. Emulators are nice to test out ideas, but make
sure the application is debugged on a real device before you call it “finished”. Of course this
applies more to actual development than to homework assignments, but it’s still a good
practice to have.
Last but not least, look things up online! There are a host of online resources out there
for Android development, I suggest using them.
(5) Incorporating Databases
Implementing databases in your Android applications is a relatively simple task,
provided that you know some basic SQL (Structured Query Language). Even without a good
comprehension of database programming, getting a database up and running is by no means a
difficult feat.
The first step is building the database itself. This can be done with the following code
snippet, placed inside the appropriate Activity:
SQLiteDatabase myDB = null;
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
where “DatabaseName” can be whatever you want to name the database.
Now that the database is created, we need to create a table, and insert some
information into the table. This is done using simple SQL commands, in the following code
snippet:
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + "Table1" + " (Field1 VARCHAR,
Field2 INT(3));");
where, once again, “Table1” can be whatever you want to name the table, and Field1/Field2
can be whatever you want to name your fields. The “VARCHAR” and “INT(3)” denote what type
of data Field1 and Field2 contain. Obviously, you can incorporate as many fields of as many
types of data as you see fit. It’s important to note that the .execSQL command can be used to
perform any SQL command which does not return data (i.e. don’t use it for SELECT commands).
Also, this specific command will create the table only if it does not already exist; it will not
delete the contents of the table, merely cause all actions to append it.
Now, to insert some data, we will use the following command:
myDB.execSQL("INSERT INTO " + "Table1" + " (Field1, Field2)" + " VALUES
('Bob', 10);");
Here, we are inserting a single entry which has Field1 equal to ‘Bob’, and Field2 equal to 10.
To access data from our table, we must use a Cursor object. Cursors are used to
manipulate database data, and are used for queries. We begin by creating our cursor, and
querying the database one of two ways:
Cursor queryCursor = null;
Here we use the standard SQL code, simply executing our query with the .rawQuery command.
queryCursor = myDB.rawQuery("SELECT * FROM Table1", null);
Here, instead of using the actual query, we let our Cursor object build the query for us, based
on our parameters, using the .query command.
queryCursor = myDB.query("Table1", null, null, null, null, null, null, null);
Both Cursor objects are equivalent, and have both executed the basic query of selecting every
row of data from Table1.
Our last step is to actually access the data. This can be achieved through a simple while
loop, and using our Cursor object to access the data for us:
String data="";
queryCursor.moveToFirst();
while(!queryCursor.isAfterLast()){
data+="{" + queryCursor.getString(0) + ",";
data+=queryCursor.getInt(1) + "}";
queryCursor.moveToNext();
}
The basic idea of this code is to use the Cursor object to return the value of each variable of
each row, store the data into a basic String variable called “data”, and then move onto the next
row. Note that queryCursor.getString(0)corresponds to the first variable, and
queryCursor.getInt(1) corresponds to the second. In this way, it is possible to retrieve each
data member individually, or simply store them all together in a String object (like we did in this
example, with the String variable “data”). The final step is to close the database, which is just a
simple, one-line command:
myDB.close();
Now that we have the entirety of database’s data stored in a String variable, it’s possible
to output it in a variety of ways, depending on what purpose the data will serve. If it’s for
debugging purposes, we can call a log statement to output the data to the LogCat pane. If
however we want to output it to the screen in an Activity, it’s simple to just use a TextView
object.
Continuing our example Activity from earlier, we can use the following code to allow us to
interact directly with the TextView object present in our XML file (the id is textview1):
TextView tv1 = (TextView) findViewById(R.id.textview1);
tv1.setText(data);
This concludes our final step, and will display each data member to the screen with the
specified formatting.
(6) Sample Code/Output
The following code encompasses everything addressed in this handout, and provides a visual
representation of the Activity as a whole:
(The XML file is the same as before – “main.xml” from Section 3 with a LinearLayout format,
and 1 TextView object with id “textview1”)
Additional Resources
http://developer.android.com/
http://stackoverflow.com/
Download