Tuesday, January 24, 2012

Back in the swing of things

To anyone that's reading this:
I do plan on writing more tutorials in the near future; I've just been REALLY busy with college, work, and activities. However, I do plan on coming back and writing more tutorials as the school year progresses. If you'd like to ask me any questions, send me a message on Reddit, my username is Leonardoty. Cheers!

Thursday, June 23, 2011

Lesson Two: Expanding upon Hello World with XML

Good Afternoon everyone:
First, in case you didn't get the notice, it may be a while before the video tutorials are up. Turns out my screen recorder of choice doesn't work with OSX 10.7, and I'm currently searching for a temporary alternative.
Second, if you haven't noticed, there is a "donate" button on the right side, somewhat against my wishes. However, it was suggested that one be added after I had "delved" into the project, so I have fulfilled that request. If you're wondering where the money goes, it will go to help cover the hosting cost of the website where all of this will be moving soon. It's more expensive than I thought it would be, and being a college student, I'd like to cover the costs from being out of pocket somehow.

Onto today's content: using more graphical interfaces with XML. This will go along with the Android Developer information, except I'm going to change things around a little bit to make it a bit more user friendly. (If you haven't checked it out, I recommend it).

If you search through the Android library, there are lots of different opportunities for you to use in your programs; we're talking anything defined to be used for the Android library. Today we'll be focusing somewhat more on GUIs (graphical user interfaces). If you're familiar with GUIs in Java, then this will be a bit easier for you.

GUIs are used in Java to bring your program away from the typical console. You can add all sorts of elements to a Java GUI; text boxes, radio buttons, select tabs, etc. As well as images, audio, and any calculations you do "behind the scenes" in Java. However, in Android, the GUI is what we'll be seeing on the screen.

If you noticed from my first tutorial, however, the code was pretty lengthy for just displaying a couple words on your screen. This is because the app was done completely in what is called "programmatic" UI. This means that the entire project was constructed using the UI source code provided by Google/Android. Anyone who's ever programmed an application like this can understand how frustrating it is; debugging can be stressful, and a small change in your source code can lead to big problems with your layout. However, there's another way to make our Android apps simpler; XML.

XML, or Extensible Markup Language, is a "set of rules for encoding documents in machine-readable form". In short, XML is meant to make projects across platforms more usable, simpler, and more generic. XML is very widely used as a standard, and many languages have been created based around XML, including RSS, Atom, XHTML, and SOAP.

So, let's look at an example of XML for an Android app; specifically the one that Android Dev provides:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"

XML files for Android (or, for anything) are fairly straightforward: it's a "tree of elements" where each node is the name of a View class. You can define custom View elements in your code, or you can use any of the classes that extend View.

The above example has just one View element, being TextView (which has 5 elements). A description of each element as such:
Attribute Meaning
This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute.
This attribute assigns a unique identifier to the TextView element. You can use the assigned ID to reference this View from your source code or from other XML resource declarations.
This attribute defines how much of the available width on the screen this View should consume. In this case, it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means.
This is just like android:layout_width, except that it refers to available screen height.
This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in the res/values/strings.xml file. This is the recommended practice for inserting strings to your application, because it makes the localization of your application to other languages graceful, without need to hard-code changes to the layout file.
Source: Android Developers

XML files can be found in your project folder, under res/layout. These are automatically created for you using the Android plugin in Eclipse. There should be one auto-generated file in your project, namely main.xml. Open the file, and replace the code inside with the following:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"

Now, inside your res/values folder, open up strings.xml. This is where you should store all your default strings. You should have two default strings already made: hello and app_name.
Revise the hello to something else; doesn't really matter, just to show you how it works. You can revise the app_name as well, but it's just a setting from when you created a project, so changing it might not be wise.

Now open your original Hello World app. In order to change to the XML format, we need to get rid of all of the TextView data we wrote yesterday (just go ahead and delete it). Instead, we want to create a contentView based off of our XML file, with this line of code:

Your autofill functionality in Eclipse should start to fill in while you type at this line. In the end, your code should look like this:
package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

Now run your app just the same, and you should see the difference.
This ends your intro into XML; next week we'll be looking other aspects of the Android SDK, such as buttons, boxes, and "toast".

Monday, June 20, 2011

Android Lesson One: Your Hello World Program

If you haven't been following my tutorials, then welcome to the first installment of the Android tutorials!
For those of you new here, this will be a series of tutorials to help you learn how to code for Android, in a somewhat timed manner - hopefully giving you more structure.
If you are unfamiliar with Java, and would like to learn Android anyways, read the last six lessons written for the basics of Java. If you'd like some more sample programs, or more difficult tests to check your knowledge, leave a comment and let me know; I'm not the best Java programmer, but my programs should at least give you some insight.

Now, onto Android. For the majority of these tutorials, I will be using the Android 2.1 SDK, seeing as it seems to be the most general. I have devices that run 1.6, 2.1, and 2.2, so I can test on each if need be.

The schedule will follow as thus: the written tutorials will come out Monday and Thursday of each week. There will be a video tutorial to go with each written one; and they will come out on Tuesday and Friday, respectively.

Today we will be simply covering the "Hello World!" program, but it will be a couple of Hello World programs into one. Seeing as there isn't just a "console" in Android like there is in Java, we'll have a couple library components we can mess with and test out.

First, I'm just going to post the code you need to enter. Essentially, we're going to walk through how each component works, to give you a better feel for how each part is described.
Here is the code:
package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {
   /** Called when the activity is first created. */
   public void onCreate(Bundle savedInstanceState) {
       TextView tv = new TextView(this);
       tv.setText("Hello, Android");

This is the code you will be using. I suggest that you re-type it, so you can better understand the meaning of each. First, though, we need to set up our new Android project.
If you have not set up Eclipse to work through these Android projects, please follow the instructions HERE.

Let's make a new Java project.
Navigate to File->New->Other, find the Android folder, and select Android Project.
Enter this information:

A quick explanation:
The project name can be anything you want.
The Build Target can be any target that you've set up; I've set pretty much them all up, but I want to use 2.1.
Application Name can be whatever you want as well; you will see it in your app.
Use the package name given: It is a predetermined package that we will use for our app.
Create Activity should be "HelloWorld" for this application.
Hit "Finish" and your project will be created!

Next, navigate to your project using the left sidebar. Under HelloWorld->Src->muo.com.helloworld->HelloWorld.java, you will find your app.

You will notice that in this project, all the code seems to be there, minus the information in the TextView.

The code that is already there is what is needed to start your "typical" Android app. However within the libraries of Android, there are lots of possibilities. In your HelloWorld folder, you should have another folder; named after the Android SDK you picked. If you look through all those possibilities, you can use any of those in your program; it's pretty awesome. But for now, we're just going to be looking at TextView.
The TextView object is your generic viewing object. To use it, we must first import that data as listed in:
import android.widget.TextView;

Just like any other object class built into Java (like the Scanner we looked at earlier, or ArrayLists, etc.) we must create a new object of that bundle in order to use it. We do so with this code:
TextView tv = new TextView(this);

The "this" refers to the path of the TextView; that is, what is going to be using it. Since it's just our screen in this app, we use "this".

Next, we need to set the text inside the TextView. What do you want it to say? You can have it say pretty much anything.
tv.setText("Hello, Leonardoty");

Finally, we must tell our Android app that we want to see this TextView. We do this using the following code:

Now, all we do is hit "run". Choose "Android Application", and after a few minutes, you'll see your app running, looking like this:

And there you have it! Your first Android app is done.
The challenge this week is to look through sidebar of Android packages. Familiarize yourself with them. Leave a comment with what you want to see looked at. Finally, if you're feeling up to the challenge, make a button out of your screen (hint; it works the same way as TextView).

Lesson Six: Introduction to Arrays, Vectors, ArrayLists, and Linked Lists

This is the final lesson on Java before we get into the actual Android Dev information.
Also, if you continue to submit the "challenges" to me, please title the email with "Android Development Challenge" so my email filter can catch it. Put the rest of your information in the body of the email.
I have not been writing solutions to each challenge; instead, I've just looked at everyone's submissions and critiqued them. If you would like solutions, I will write them up and post them.
When looking at storing multiple fields of data in one infrastructure, or keeping "linked" data together, there are multiple different ways that this can be accomplished.
First, you can store data in multiple individual data fields. However, we won't be looking at this, because this is typically a pretty bad idea; storing data that should be linked in multiple data fields connects them in no way, and they can easily be lost, changed, or accidentally deleted. Therefore, Java has provided us with multiple ways of fixing this issue; that is, Arrays, Vectors, Array Lists, and Linked Lists. Each have their advantages and their disadvantages.


First, let's take a look at arrays. Arrays are a container that can hold a fixed number of values of a single type, whether that be String, int, or even your own Object of creation. Once an array is created, it has a fixed length; in order to make your array bigger, you must create a new array (usually double in size), copy the items from the first array into the second array, and delete the first array.
Data in an array is accessed by looking at the index. Indexes start at 0, and end at the length of the array minus 1. You can add data to the array by entering the index, using a for loop, or other methods. Here is an example of an array of integers, size 10, in Java:
First, we need to import the correct library as such:
import java.util.*;
Now, we must create a new object of the array.
int[] integerArray = new int[10];
for (int i = 0; i < 10; i++)
     integerArray[i] = i;
In this instance, we have declared the data in each index in the array equal to index itself (that is, at position 0, the data is "0"). You can make an array of any single data type. If you make an Object of cars, containing weight, size, color, and seats, you can make an array of this object as well. Arrays can also be multi-dimensional. A 2-D array can be used in replacement of using an object. For example, a 2-D array could be used such that each entry of the first array holds the data for each car, and each entry in the second array holds color, size, seats, etc.

Vectors and Array Lists

Vectors and Array Lists are very similar; in fact, they're almost identical. When trying to decide whether to use Array List or Vectors, there are 3 factors that we must consider; synchronization, data growth, and usage patterns. The biggest difference between the two is that vectors are synchronized (that is, the data is thread safe) whereas Array Lists are not synchronized. If you're looking at these differences on whether to choose Vectors or Array Lists, you probably don't need to be reading this tutorial. In most college courses, they will tell you to use Array Lists, and in fact, we were told to "never use Vectors". The Array List is like an Array, except it utilizes the List interface. This makes things much easier to do, but also much slower. An Array List does not need a size; it creates a size itself, and will increase the size as it is needed. You can add, delete, and check if the array isEmpty. However, to go through all the elements of the array, we must use an iterator (which will not be covered here) because the size is unknown. Here is an example of an Array List in Java:
import java.util.*;
ArrayList myArrayList = new ArrayList();
(Please ignore the closing "string" tags; it's a fault of the brush and using Array List syntax.) Here we see 3 methods built in to the List interface; add, remove, and get. There are even more methods relating to the List interface; you can find them on the internet. Please be advised that an Array List stores data only as an object reference. Therefore, you cannot create an Array List of type int, or double; you must use the wrapper classes included in Java, those being Integer or Double respectively.

Linked Lists

We won't cover Linked Lists in depth, just conceptually; Linked Lists are a somewhat difficult topic (for this need, at least). Linked Lists work by connecting each entry to one another, in a linear form (this form can be one direction, forwards and backwards, circular, etc.) To create a Linked List, you must have an element be first; that is, a head. This head is a node element, meaning that the node points to the next item in the linked list, and also contains the reference to the data. To add an item to a Linked List, you simply connect the last element (the tail) to the new element, and set the new node to null, as this will be the new tail. BE ADVISED that to reach ANY data in the linked list, you must iterate through the whole thing, making it very slow. Also, you must use a node outside of the linked list to iterate; if you use the head element, you will effectively delete your linked list.

That's it for this lesson; there is no challenge for this, as it would be pretty difficult to do. More Android content to come today!

Tuesday, June 14, 2011

Lesson Five: Iteration vs. Recursion

Happy Tuesday everyone.
Reminder: Android specific content will begin ONE WEEK FROM YESTERDAY.
For those inquiring about the Google Calendar; it's not something you can just "view", aka clicking on it will not work. You must copy the link and add it to your calendar list. That's the only way Google Calendar works.

Also, thank you to those that have been sending me submissions; I'm sorry if I haven't gotten back to you quite yet, but I promise I will by tonight. I will be caught up by tomorrow morning.

Now onto the lesson; the difference between iteration and recursion.
In Java, there are two major ways in which we can progress through a solution if we want to do it "over and over", and that is iteration and recursion.

Iteration is just like a for loop; you go through an entry one at a time until you reach a stopping condition. For example, we can write a for loop to count the numbers 1 through 10:

for (int i = 0; i <= 10; i++)
This would do the trick both quickly and efficiently. However, there are some cases where an iterative function is not the best choice. A recursive function is a function that breaks down a problem into smaller and smaller pieces so that it can be handled effectively. This is done by the method calling itself. The advantage of writing a recursive function is that it is very powerful, and can do things that iterative functions cannot do [easily]. However, this is taken with a grain of salt, as recursive functions are VERY process intensive. NOTE: If you can ever use an iterative function, use it instead of a recursive one, if applicable. There are multiple parts to a recursive function. 1) A base case which always returns a solution or a "not found" solution. 2) A way of reducing the problem from the original to a smaller problem, ending in the base case. 3) The actual recursive call. Recursive functions can be difficult to write; especially because it can be difficult to figure out why your function isn't working. Often times, if your function doesn't reach the base case, it will go into a never ending loop, typically crashing your program. Let's write a simple recursive function to do the same thing our iterative function did; print out the numbers 1-10.
public static void countUp(int start)
     if (start > 10)
          countUp(start + 1);
Although this is a recursive function, it's not a very good one; as there is a way to do this iteratively (however, it's just an example). This is just an introduction into how recursive functions work. There are many example online as to more complex recursive functions (and trust me, they can get very complicated). This week's challenge: write a function that prints out the Fibonacci Sequence up to 144, and email it to leonardoty@gmail.com.

Thursday, June 9, 2011

Lesson Four: Writing your own methods

Afternoon everyone!
No new news today, as I don't really have many updates. The website is still in the work, and although things are going slow, I hope to have SOMETHING up soon. We'll see how things go.

Onto methods. Methods are very handy in learning Java. At my Uni, they didn't teach how to write your own method in Java I, which I wish they would have, because it would have made things a lot easier.

The purpose of writing your own method is to eliminate code reuse, to make your program simpler, and easier to read/debug. Writing your own method allows you to write a bit of code that has input variables, a return type, and some sort of code to execute. Then, in the main of your program, you simply call your method as many times as you want, and it will do the rest.

Java methods are written inside the class declaration, but typically above the main class (below the loop in C programs). A method declaration would look something like this:
access_modifier (additional_modifiers) return type (parameter_type parameter_name, parameter_type parameter_name, (etc)){

Each of these serves a different purpose.
Access Modifier: This tells who is allowed to access the method. Private, Public, Protected, and Default (no modifier) are your options.
Additional Modifiers: Use these when you want to make a method static, abstract, etc.*
Return Type: This is for what the method will be computing and returning. It can be a String, int, double, etc. or void, if it will have no return type.
Parameter Type/Parameter Name: These are the variables you'll be "passing in" to your method. The type is what type of variable it is; String, int, etc. The parameter name is simply what you name it; it can be anything, but you will use it throughout your method.

So, let's say we want to write a method to add two numbers together. we'll be using integers, and we'll be returning an integer. Our method would look something like this:
public int computeAddition(int numberOne, int numberTwo)
     int numberThree = numberOne + numberTwo;
     return numberThree;

This method takes in two integers, and returns an integer. in order to use this method, we simply set a variable to it's value. For example:
int num1 = 10;
int num2 = 13;
int num3 = computeAddition(num1, num2);

From this, num3 will be 23, as it adds the two numbers together. Although this isn't necessarily helpful, it demonstrates how to write your own method.
Writing a method can be very handy. You can use them to do complex computations, computations that must be done over and over, for code reuse/clarity, printing lines over and over again, etc.

And that's it. Methods are very handy for multiple applications in Java.
Challenge: Write a method that takes in a number, and counts from that number, down to 0 (use a for loop or a while loop; either will work) and print it to console.

Monday, June 6, 2011

Lesson Three: Loops and Scanners

Happy Monday everyone! First off, some business.
I'm starting to design the "official" website of the project, so people can continue to work through things after the summer is done. If you have any suggestions, I'd appreciate you leaving me some feedback in this thread.
Next, the Google Calendar is up at this link. Simply add it to the list of your calendars in Google and you'll receive updates.
My plan is to have an update Monday and Friday. This will become more frequent after the website goes up. Videos will come out on the same day, however, I won't start making videos until we get into the actual Android development.

Today, we're going over loops and console input (scanners).
Loops are very handy if you need to go through a set of data so many times. There are 3 major types of loops; for-loops, while-loops, and do-while-loops. For loops are very handy, in the fact that you go through them a specific number of times. This is called a control loop; you know how many iterations you go through for the loop. In order to create a for loop, you need to have a stopping condition; something that tells the loop no more looping. You also need something to keep the loop iterating. Look at the following example.
for (int i = 0; i < 10; i++)
For those of you with little coding experience, look up how to tab your code when you type it out. Unfortunately, tabs don't appear very well in blog quotes, and I haven't found anything to do other than take pictures (which I'm avoiding). It's helpful to know that when you're writing for loops, the brackets aren't necessary if the condition within the loop is only one line. That is, you can do this:
for (int i = 0; i < 10; i++)
But you can't do this:
for (int i = 0; i < 10; i++)
System.out.println("Loop again!");
As in this example, it will write "Loop!" 10 times, but only "Loop again!" once. To include both in the loop, you need braces. It's good practice to just use them all the time, but not necessary. While-loops, on the other hand, are sentinel controlled. This means that you don't have an exact number of when it's going to end, but it needs a stopping condition; a typical use of this is iterating through a document, pulling in data line by line, until there is no data (otherwise, you will receive Java runtime errors). An example of a while-loop:
int i = 0;
while (i != 10)
Obviously, in this example, we know when the data is going to end, but later on I will show you an example where that's not the case. This is just the syntax. There is also a type of while-loop called a do-while-loop. The difference is, a while-loop may not iterate at all, whereas a do-while-loop must iterate AT LEAST once. Now, onto console input. We'll just cover Scanners for now, as there are other methods. Scanners allow you to enter data into the console, and your program can interact with them. They *do* have other purposes, but they all relate to input of some sort, or reading data. To use a scanner, you first need to import the scanner library. at the top of your program, write:
import java.util.*;
Although the scanner is located at "java.util.scanner", it's easier to just import the whole library; it won't actually slow down your program, Java is very good at using only what it needs. To create a Scanner, we need to call the constructor in the java class with the following code:
Scanner [scannerName] = new Scanner([input here]);
scannerName is where the name of the scanner you want goes, and the input is where you'd like to get your input, whether that be a file, another class, and array, etc. But for today, we're going to be using console input. We also need somewhere to store the data. A string, an integer, it doesn't matter; just know whatever one you pick, the Scanner input needs to match it (eclipse will help you with this).
String input = ""; 
Scanner scanner = new Scanner(System.in);
input = scanner.next();
With this, whatever you type into console and hit "enter" will be stored in input. You can continue this, to take in data. Now, to put it all together. We're going to use a while loop to take in data fro the keyboard until the user enters "0".
Scanner scanner = new Scanner(System.in);
int input = -1; 
input = scanner.nextInt();
while (input != 0)
     System.out.println("Enter 0 to exit the loop.");
     input = scanner.nextInt(); //without this, you will hit a loop that never ends. 

And that's it! For loops, while loops, and a Scanner to use input. You can use scanners within scanners, and loops within loops, in order to pull in data. You can also use multiple data types for inputs.

Wednesday, we will be looking at writing your own methods.

Challenge: Use a scanner to input numbers, and do some math functions on them; addition and multiplication for starters. Email your submissions to leonardoty@gmail.com.