Android Snippet: Adding an External .jar to your Project

Android snippets are a new section of Droidweb which detail a simple process in Android Development. However, in spite of their size, don’t dismiss these mini-tutorials! The methods they describe are pretty handy for any serious Android developer. Got an Android tip / trick you’d like to see here? Leave us note in the comments below or tweet @droidweb!

Occasionally you’re going to need to reference other people’s code (OPC) in your Android projects.  Usually this is done in one of two methods: either you import the other project as a library project (if you’ve ever used ActionBarSherlock, you’ve done this), or you include the project as a .jar file.  In today’s Android snippet we’re going to focus on the later.  The process is really simple (a drag n’ drop and a right click is all you need to do), but not doing this properly can lead to headaches at run time.

Things you’ll need:

  • .jar file of the library you intend to import.  Usually this is a downloadable from the site of whatever project you’re making use of

Steps

  1. Copy the jar to your Android project’s /libs folder
  2. Right click the jar and choose “Build Path > Add to Build Path’”
  3. You’re done.  Happy Coding!

Thanks to Vinayak.B over at stackoverflow for this quick tip.  See original post.

Fix @Override Errors in your Eclipse Console

Often when importing Android code into my Eclipse workspace, I find that there are a lot of new ‘errors’ introduced to the code.  These errors were closely linked to my overriden classes (something you’ll find quite often in android code) and read “The method X must override a superclass method” .  For the longest time I’ve wondered how to reliably fix those bugs (until now I had been removing and re-adding the @Override keyword as appropriate to make the compiler shut up).  This morning I stumbled across a Stack Overflow thread that finally solves this problem.

You see, the problem is related to which version of Java the code is checked for compatibility errors against.  Eclipse defaults to using Java 1.5, which only allows the use of interface methods if super() is called.  Java 1.6 allowed the use of the @Override keyword to designation the interface implementation which is current standard way of overriding interface classes in Android coding.

To fix your problem you just need to do a bit of tinkering in the project settings in Eclipse.  Go to your project preferences and under Java > Compiler set the java compiler to 1.6.  While this might fix the error, it is more likely that you’re going to have to change the project specific value for compiler level as well.  Select ”Configure project specific settings” and change the java compiler value there to 1.6 as well.  After an automatic rebuild of your project, you should see all of those pesky error messages disappear!

Starting Android Development Part 3: Layout Tutorial 2

As promised, here’s part two of my coverage on layouts in Android.  Lets pick up where we left off, namely we just created a main.xml file for layout of our temperature conversion application.

So you know what we’re trying to achieve here, here’s a screenshot of the final product.

temp_screen_final

I know what you’re thinking.  That’s not that cute of a layout.  I’ll leave the job of making really pretty layouts to you after you learn the basics.  For now this layout will do to show you how making layouts in Android works.

This layout consists of a TableLayout (A Linear Layout could have done here as well).  Each table row has other items embedded in it.  One row even has a TableLayout embedded within it (just to show that you can do this).  This is a valid layout, but is generally frowned upon, as embedding table layouts within table layouts can lead to slower UI performance in the long run.

Here’s the code for the layout:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout
android:id="@+id/widget45"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0000ff"
android:padding="10px"
android:text="Temperature Conversion App"
android:textSize="18px"
android:typeface="sans"
android:textStyle="bold"
>
</TextView>
<TableLayout
android:id="@+id/widget62"
android:layout_width="319px"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TableRow
android:id="@+id/widget63"
android:layout_width="149px"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/User_input_F"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text=" "
>
</EditText>
<TextView
android:id="@+id/widget78"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ºF)"
>
</TextView>
</TableRow>
<TableRow
android:id="@+id/widget64"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/User_input_C"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text=" "
>
</EditText>
<TextView
android:id="@+id/widget79"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ºC)"
>
</TextView>
</TableRow>
<TableRow
android:id="@+id/widget65"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/widget83"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text=" "
>
</EditText>
<TextView
android:id="@+id/User_input_K"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(ºK)"
>
</TextView>
</TableRow>
</TableLayout>
<TableRow
android:id="@+id/Conversion"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/conversion"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Convert to:"
>
</TextView>
<RadioGroup
android:id="@+id/widget144"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<RadioButton
android:id="@+id/F_Select"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fareinheit"
>
</RadioButton>
<RadioButton
android:id="@+id/C_Select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Celcius"
>
</RadioButton>
<RadioButton
android:id="@+id/K_Select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kelvin"
>
</RadioButton>
</RadioGroup>
</TableRow>
<TableRow
android:id="@+id/widget84"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/Calculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
>
</Button>
</TableRow>
</TableLayout>

Note how each element has an id attribute (android:id) and the value of that attribute starts with “@+id/name“@+id/” identifies the name by which you can refer to this
layout element later in your java programming.  Other things to note include:

  • android:layout_width and android:layout_height: Use these to determine how much space an element is going to take up.  These can have two values: wrap_content and fill_parent.  Wrap content means the element will only be as large as it needs to be to display its content.  Fill_parent means the element will fill all available space it can, as determined by the parent element it resides in
  • To find the attribute applicable to a given layout, check out that layouts documentation at the developer.android.com/reference website.  E.g. the API site for TableLayout is
    http://developer.android.com/reference/android/widget/TableLayout.html. I usually find the page i need by just searching “android layout” and the name of the element I’m using

In the next post of this series I will discuss some common Android layout elements, what they look like, and some of the attributes associated with that element.  Then it’ll be time to connect our layout (frontend) to the logic that makes it work (the backend).  For now check out the code I provided, try to understand how it works, and practice creating your own Android layouts!

Starting Android Development Part 3: Layout Tutorial 1

Now that I’ve bored you to death with details about how Android programming works, lets actually put something together, shall we?  This post will deal mainly with creating layouts in Android and will finish up with a sample layout for our Temperature Conversion project.

For what Google has to say about layouts check out their developers site at http://developer.android.com/guide/topics/ui/index.html.

Now let me explain a little of what you read.  Layouts for Android screens are described in XML files in your /res/layout/ folder.  The XML file describes a hierarchy of layout elements.  The higher level elements determine the where of your layout and the lower level elements within these elements determine the what of your layout.

Ok that was a mouthful.  Lets look at the simple example Google provided:

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView android:id=”@+id/text”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hello, I am a TextView” />
<Button android:id=”@+id/button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Hello, I am a Button” />
</LinearLayout>

The Linear Layout describes the where, e.g. how the elements within this tag are going to be positioned in relation to each other.  TextView and Button are two lower level elements which are UI elements the user will interact with (a box in which to enter data and a clickable button, respectively)

The result of that layout is listed below.  Note the fact that Linear Layout makes the elements line up one below another (We’ll get into the alternative options later).

Click Me to Make Me Bigger!

Armed with this knowledge, lets try to make our own Layout.

  • Go to File > New > Other
  • Click on Android > Android XML file
  • Click Next
  • In the resulting screen fill out the following values:
  • Project: Click Browse and select the project you want to associate this XML file with (for this demonstration it would be whatever you named the temperature conversation application project)
  • File: Call this file main.xml
  • Click Layout for the type of resource
  • Choose Linear Layout for the root element of the XML file

Everything should look similar to the screenshot below:

Picture 5

  • Click Finish

In the coming posts in this series I will go over an actual layout and discuss some of the common layout elements for Android programs.  Stay Tuned!

Starting Android Development Part 2: Project Structure

In Part One of Starting Android Development, we discussed setting up your project in Eclipse.  Now it’s time to explain exactly what’s going on and how Android development works.  This information will help you keep things in perspective as you program, and it will help you when it comes to debugging time.

Let’s take a look at the Eclipse screen after you’ve set up a given project:

Picture 6

For the purposes of this explanation, let’s look at the directories in the left pane of the Eclipse screen.  Under the name of the project you’ve just created, you should see several subfolders.  Let’s explain what they do:

  • src: This holds the source code for your project.
    • com.droidweb.conversion: This is the package holding your source code.  Several packages can make up a single project.  This is especially true when you include others’ packages to provide some type of functionality for your program.  For example, in a conversion application I wrote (ConvertAll+), I imported a package to handle different currencies.
      • convert.java: Inside the package are individual .java files.  This is where the goodies (the source code itself) are.
  • gen: This is a folder for automatically generated stuff Android uses to help your program operate properly.  There’s nothing in here that you need to mess with.  It will automatically update itself as necessary.  Sometimes when you import projects and they return errors, the solution is to delete this folder and let Eclipse regenerate it for you . . . but more about that later.
    • com.droidweb.conversion: This is the package holding automatically generated code corresponding to the package of the same name in the /src/ folder.
      • R.java: R.java is an automatically created and maintained file that keeps up with the resources your project utilizes.  In a lot of your Android programming, you’re going to use static variables that really translate into numerical (usual hex) values.  R.java makes the translation between these variables and their numerical values.
  • Android 1.5 (or appropriate Android source version): This contains the actual Android source code on top of which you’re going to build your applications.  As such, I’m not really going to discuss this much.
  • assets:  Why, this is what you set your — oh wait — wrong thing. . . . Usually you won’t mess with this folder, but if you have raw files to be read by your application, then they can be put here; but it’s probably better that it goes in the /res/raw folder.  More about that later.
  • res: res stands for resources.  Here is where you put your resources (images, files, etc).
    • drawable: This is where the images you’re going to use go.  Android supports a variety of image files, including .jpg, .gif (static), png, etc.
    • layout: This is where the .xml files describing your program layouts go.  I’ll spend a post on those later.
    • values: This is where .xml files defining values can be stored.  An example is a network topography program I worked on.  In the custom view drawing routine, I predefined the colors of good / bad links in a .xml file in the /srv/values folder.
  • AndroidManifest.xml: This is the file that will be the source of the most headaches for you (well, starting out it will be . . .).  This is where your project is described in a form that Android devices can understand.  Application permissions, activity descriptions, and more are found here.  This file itself will be the topic of a future post onto itself — yes, it’s that important.

Next time we’ll discuss program flow in a typical Android program.

Learn Android Basic Programming Skills via Android Competency Center

Here’s a site I’ve enjoyed the use of.  Android Competency Center is a android related blog that focusses on just that; being competent in programming for Android.

Tutorials include helpful snippets about:

Lately I’ve found myself relying on this site more and more for simple tutorials to quickly create certain functionality in my programs. Hope you enjoy it!


Developer Tip #6: Programmatically Reading and Writing From SD Card

Here’s a little low-level tutorial that I think will make your lives easier.  What the use in enabling your SD card in a development environment, if you don’t know how to read / write to said drive?  Well have no fear.  Here’s a condensed, simple method for doing just that.

private void WriteToFile(String what_to_write) {
        try{
            /* Environment.getExternalStorage Directory calls the SDCard’s filepath, which may change per device */
            File root = Environment.getExternalStorageDirectory();
            //if we have permission to write to this drive…
            if(root.canWrite()){
                File dir = new File(root + "where_on_the_SDCard_do_you_want_to_write");
                //
                File datafile = new File(dir, number + ".extension");
                FileWriter datawriter = new FileWriter(datafile);
                BufferedWriter out = new BufferedWriter(datawriter);
                // More likely is going to be a loop that writes consecutive entries of data
                out.write(what_to_write);
                //remember to close what you open…
                out.close();
            }
        }catch(IOException e){
            Log.e("Whoops", "Can’t write" + e.getMessage());
        }
    }

Ok… now that we can write to file… how about reading from that file?  See below:

/*calling SD drive… you can replace w/ whatever path you want */
File f = new File(Environment.getExternalStorageDirectory().getPath() + "your_path" + ".your_extension");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String read = new String();
while((read = buf.readLine())!= null){
    //Do Something Which each line of data read
    parse(read);
}

Find Android Tutorials at Tactel US Developer Corner (TDC)

Looking for a source of comprehensive Android tutorials? Check out Tactel‘s US Developer Corner (TDC). This is a brand new site (It just went live Monday) focusing on the Android platform and providing Android Developers tutorials. From the mission statement on the site:

Mission Statement

The goal of the Tactel US Developer Corner is to inform and educate all developers from beginners to advanced skill levels about leading edge techniques and best practices with Android and beyond. Through in-depth tutorials and sample source code you will learn advanced topics and gain a new found ability to express your ideas whether it be a 2D or 3D game or another innovative application. The Tactel US Developer Corner provides a community and networking resource so you can meet like-minded individuals and perhaps team-up to make the next great application. Get ready to download some leading edge code, meet new friends, and development partners; including us…

One of the first projects of this site is to provide a tutorial on how to make a 3D FPS for Android! I spoke with Michael Leahy of Tactel, and he said to “expect the first tutorials to appear by the end of the week and constant release after that in the coming 2-3 months”. Be sure to check this site and check it often.

P.S. If there are any tutorials you would like to see, post here and we’ll try to provide them for you either though TDC or other means.

TDC

About Tactel:

Tactel is a leading developer of mobile applications, providing solutions and consulting services to many of the worlds major network operators and mobile handset vendors. We help these customers stay ahead of the game by designing genuinely original applications, and making sure they work on all networks and with all handsets.

Android Development Tip #2: Reading an Input Stream

Commonly I have found myself sending HTTP POST / GET requests. In this process it is helpful to quickly see the response the phone receives to said request. Whether it be for debugging purposes or to aid with the writing of a parser, I have commonly used the following snippet to read the input stream received from a HTTP request.:

public static String ReadInputStream(InputStream in) throws IOException {
StringBuffer stream = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
stream.append(new String(b, 0, n));
}
return stream.toString();
}

Place this at the bottom of the class you want to use it in and call simply by using:
//Log.d("Input Stream Results", ReadInputStream(stream));

BONUS:
Here’s some code that takes care of calling a URL, and getting the response:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(/* URL HERE */);
HttpResponse response;
try {
response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
Log.d("response", stream_reader(stream));
} catch (ClientProtocolException e) {
//Handle not connecting to client
Log.d("ClientProtocolException Thrown", e.toString());
} catch (IOException e) {
//couldn't connect to host
//TODO: HANDLE NOT CONNECTING TO CLIENT
Log.d("IOException Thrown", e.toString());
}

Next Post: Handling HTTPS:// connections.

Widgets Tutorial Part 1: Planning

About a week or two ago, we bought you an article about the support of widgets in Google SDK 1.5. In that same article I mentioned the Droid Dev challenge sponsored by Android-dls.com. I’m using this competition as an opportunity to provide a tutorial for creating widgets that builds upon the existing information.

First, a disclaimer. Don’t use this tutorial in lieu of the quality information already out there. This tutorial is going to be condensed at best. I recommend checking out

Ok, ready to begin?  First, I suppose, you need to come up with a widget idea.  My widget idea comes from a response to a blog post I made on Google And Blog. One user speculated that it would be useful to have a live folder for last x-number of unread e-mail. I’m going to apply that idea to a widget. Lets aim for a widget that shows your last unread e-mail, and upon clicking expands to show your last screen-full of unread e-mails, and has an option to go to either the gmail application, or the m.gmail.com website.

Next Post: The Androind manifest.xml file