Ads

Monday, 20 October 2014

Saturday, 6 September 2014

Error Free Android Hello World Project on Eclipse

Removal of two common errors that may arise when running the android project on eclipse.
[ PANIC: Could not open: C:\Users\gTiwari\.android/avd/MyAndAVD.ini ]
and
[ invalid command-line parameter: Files ]

Today I tried to setup the essentials and test a demo project on Eclipse.I installed required tools (Android SDK, ADT, etc) and created a empty project successfully.

I was following these articles :
Installing Android SDK and ADT in eclipse.
Android First HelloWorld App in Eclipse.
But I  got the few errors when I tried run the Hello World project that eclipse created for me.

In this Blog, I am  describing the errors and how I solved them that may be useful for Android beginners like you.

[My System Details : Windows 7(64-bit). Eclipse 3.7 (Indigo).The MyFirstEmul is the name of emulator I created.]

Error #1
When i created a hello world project and tried to run it. I got the following error.
[2011-08-27 18:05:22 - Emulator] PANIC: Could not open: C:\Users\gTiwari\.android/avd/MyAndAVD.ini
Cause : 
The emulator could not found in location "C:\Users\gTiwari\". I searched over my HDD for the emulator I created earlier. And I found it in the  E:\ .android folder. This might be due to I had moved my system folders such as Documents, Desktop, Downloads to E:\.
Solution :
I simply moved the E:\.android folder to C:\Users\gTiwari\ and solved it.

Error #2
After I solved the Error #1, and tried to run the project, I got the following error :
[2011-08-27 18:24:39 - Emulator] invalid command-line parameter: Files.
[2011-08-27 18:24:39 - Emulator] Hint: use '@foo' to launch a virtual device named 'foo'.
[2011-08-27 18:24:39 - Emulator] please use -help for more information
Cause : 
The default installation location is: C:\Programme Files(x86)\Android\android-sdk.  But the  SDK location cannot contain any spaces.
Solution : 
Should I reinstall the Android SDK to new location with no space in folder names ?
Well, that may be a solution. But i found easy solution for this.
I make use of mklink command line utility of NTFS in Windows 7 (in previous versions of the command may be different). I pointed C:\AndroidSDK to the actual C:\Program Files (x86)\Android\android-sdk by using following command.
     MKLINK  /J  C:\AndroidSDK "C:\Program Files (x86)\Android\android-sdk\"
This command created special junction folder C:\AndroidSDK helped me in  redirection.

And I configured this new path(C:\AndroidSDK) to AndroidSDK in Eclipse IDE settings - from
                      Windows -> Preferences -> Android
And run the Hello World project successfully.

Android Code: Latitude and Longitude of the mobiledevice

We should use the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to therequestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
Required Permission :
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

My first Android project in Eclipse: Multiplication Table Generator App using TextWatcher and OnClickListener

After removing the configuration errors that came during running the auto generated Hello World project, I decided to write a Multiplication Table Generator App on Android platform. This is my first android app other than HelloWorld. In this article, I am going to explain how I created the App. It describes the use of TextWatcher and OnClickListener interfaces for event handling.

Multiplication Table Generator contains the EditText-ipNumberTxt component for reading user input – a number. It contains two Buttons '+' and '–' to increment/decrement the number in EditText. The generated output is displayed in TextView-outputTXT. The multiplication table is generated on afterTextChanged event of EditText field.

The download link for complete project is given at end of article.

AndroidManifest.xml file :

An Android application is described the file "AndroidManifest.xml". This file must declare all activities, services, broadcast receivers and content provider of the application. It must also contain the required permissions for the application.
Make sure the AndroidManifest.xml file contains following piece of information.
    <application android:icon="@drawable/icon"
    android:label="@string/app_name">
        <activity android:name=".FirstAndroid1Activity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

GUI Creation

GUI creation is done via the rich editor provided on ADT. The GUI code generated in XML works much similar to HTML.
The UI contains RelativeLayout for control Buttons, EditText and upper TextView component. For displaying output
The UI("res/layout/main.xml") has following Structure:
<LinearLayout>
<RelativeLayout>
<TextView> App Name at Top </TextView>
<Button> + Button </Button>
<EditText> Input Text Field </EditText>
<Button> - Button </Button>
</RelativeLayout>
  <TextView> Result Area </TextView>
</LinearLayout>

String attributes

Android allows you to create attributes for resources, e.g. for strings and / or colors. These attributes can be used in your UI definition via XML or in your Java source code.  The file "res/values/string.xml" contains such attributes.
Our string.xml file :
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Welcome to Multiplication Table App</string>
    <string name="app_name">Multiplication Table</string>
    <string name="genButton">Generate Table</string>
    <string name="inc">+</string>
    <string name="dec">-</string>
</resources>
These string resources are applied to UI components using following tag :
android:text="@string/NAME_OF_ATTRIBUTE_ON_STRING.XML_FILE"
eg : The following sets ‘+’ to incButton.
<!-- Increment Button -->
<Button android:id="@+id/incButton"
  android:text="@string/inc">
</Button>

Main Activity Class

Activity represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.
// FirstAndroid1Activity.java
public class FirstAndroid1Activity extends Activity {

     Button incButton, decButton;
     EditText ipNumberTxt;
     TextView outputTXT;
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         // get resources
         incButton = (Button) findViewById(R.id.incButton);
         decButton = (Button) findViewById(R.id.decButton);
         ipNumberTxt = (EditText) findViewById(R.id.inputNumber);
         outputTXT = (TextView) findViewById(R.id.outputTXT);
     }
}

ButtonClickListener for INC/DEC buttons

To change values to ipNumberTxt on  onClick event of incButton and decButton, create following class MultiplicationTableButtonClickListener which implements OnClickListener interface.
// MultiplicationTableButtonClickListener.java
public class MultiplicationTableButtonClickListener
implements OnClickListener {
     EditText valueField;
     boolean isIncreaseBtn;
     public MultiplicationTableButtonClickListener(
EditText valueField, boolean isIncreaseBtn) {
         this.valueField = valueField;
         this.isIncreaseBtn = isIncreaseBtn;
     }
     @Override
     public void onClick(View v) {
         String strVal = valueField.getText().toString().trim();
         int intVal = 0;
         if (!strVal.isEmpty()) {
              intVal = Integer.parseInt(strVal);
         }
         // change value, do not need to calculate multiplication table
         if (isIncreaseBtn) {
              valueField.setText(String.valueOf(++intVal));
         } else {
              valueField.setText(String.valueOf(--intVal));
         }
     }
}
Add following code to FirstAndroid1Activity class
     incListener = new MultiplicationTableButtonClickListener(ipNumberTxt, true);
     decListener = new MultiplicationTableButtonClickListener(ipNumberTxt, false);
     incButton.setOnClickListener(incListener);
     decButton.setOnClickListener(decListener);

The multiplication table logic :

Create a class with public static String getStringTable(int n) method.
// MultiplicationTable.java
public class MultiplicationTable {
     public static String getStringTable(int n) {
         StringBuilder sb = new StringBuilder();
         for (int i = 1; i <= 10; i++) {
              sb.append(n + " x " + i + " = " + i * n + "\n");
         }
         return sb.toString();
     }
}

TextWatcher Implementation :

To generate multiplication table on afterTextChanged event, create following class MultiplicationListener which implements TextWatcher interface.
// MultiplicationListener.java
public class MultiplicationListener implements TextWatcher {
     TextView textView;
     EditText valueField;
     public MultiplicationListener(TextView textView, EditText valueField) {
         this.textView = textView;
         this.valueField = valueField;
     }
     @Override
     public void afterTextChanged(Editable s) {
         String number = valueField.getText().toString().trim();
         if (!number.isEmpty() && !number.equals("0")) {
              textView.setText(MultiplicationTable.getStringTable(Integer.parseInt(number)));
         }
     }
     @Override
     public void beforeTextChanged(CharSequence s, int start, int count, int after) {  }
     @Override
     public void onTextChanged(CharSequence s, int start, int before, int count) { }
}
Add the following lines of code on FirstAndroid1Activity class 
// TextWatcher listener
MultiplicationListener mulListener;
mulListener = new MultiplicationListener(outputTXT, ipNumberTxt);
ipNumberTxt.addTextChangedListener(mulListener);
NOTE: In MultiplicationTableButtonClickListener, we just change the value on input fields. The generation of new table is done automatically because we are adding MultiplicationListener(implementation of TextWatcher interface).
The First App is ready !

Tuesday, 5 August 2014

GAME DEVELOPMENT TUTORIAL: DAY 2-10: Painting Tilemap


Hello and welcome! This is the last lesson of Unit 2.

More fun is just around the corner in Unit 3. Let's finish strong!

In today's lesson, we will be building upon what we covered in Day 9.
If you have not looked at Day 9 yet, please do so before proceeding!

What we will be covering:
1. We will be creating a two-dimensional Array that holds a random set of values.
2. Using this two-dimensional array, we will print colored squares to the screen.

What is the significance of this lesson?
When we continue our 2D game development, we will be creating levels (maps) using text files. In each text file, we will represent objects in the game with keyboard characters, and our game will parse the file to create levels that we can interact with.

This lesson will be an application of what we learned in Day 9. After this, we should be able to accomplish the above task with ease in the coming lessons.

Note: We will be creating a NEW class today. You do not need to open any previous files.
Let's begin.

Lesson #2-28: Creating the Tilemap
1. Begin by creating a class named Renderer in any test Project. (Tip: You can create a new Project by right-clicking on the Package Explorer >> New >> Java Project.)

2. Extend Applet and import it.- add "extends Applet" at the end of the class declaration.
- Press Ctrl+Shift+O to organize imports automatically.

It should look like this:
import java.applet.Applet;

public class Renderer extends Applet{

}

3. Override the init() and paint() methods.
Since we have extended an Applet (inheritance), Java will look for the paint() and init() methods. As we will be defining these methods ourselves rather than using the one in the Applet method, so we use the "@Override" keyword.

The two methods will look like this (Make sure to import Graphics) (changes in Bold):
import java.applet.Applet;
import java.awt.Graphics;

public class Renderer extends Applet{

@Override
public void init() {

}

@Override
public void paint(Graphics g) {

}

}
4. Define the init() method.


In the init() method, we want to do the following:

- Set the size of the window.
- Set the color of the Background
- Create the Tilemap.

So we add the following lines of code:

setSize(800, 480);
setBackground(Color.BLACK);
createTilemap();

Eclipse will give you an error as follows:
Since we have never created a createTilemap() method, we must do so right now.

5. Click on the 1 quickfix: Create method 'createTilemap()'.

This should create a method as follows:


private void createTilemap() {


}


We must do two things in the Tilemap() method.
1. We need to create a two-dimensional array. We will call it tilemap and call its height rows and its width columns.
2. Using a random number generator, we will fill tilemap with integers between 0 and 4, inclusive.



Let's do these two things:

1. Creating a 2D Array
Before we begin, to make things easier, we will create three static variables at the top of the class.

- Directly below "public class Renderer extends Applet {", add the following:


   static int[][] tilemap;
   static int rows, columns;

This creates a static (class-wide) two-dimensional Array called tilemap and two integers called rows and columns.

Scroll back inside the createTilemap() method. We will now define the three variables by declaring the following:


   tilemap = new int[50][30];
   rows = tilemap.length;
   columns = tilemap[1].length;


- The first line creates a new 2D Array with 50 elements, which each contain 30 elements.
- tilemap.length is 50, as tilemap contains 50 elements.
- Each of these 50 elements contain 30 elements. Therefore, tilemap[1] refers to the element with index 1 in this 50 element list (the second element of fifty).

Note: Remember that indexes start at 0.
Note 2: We can refer to all 50 elements in tilemap using the indexes: 0 through 49.

2. Randomly Fill tilemap Array


- To fill the tilemap Array randomly, we first create a new Random object:
Random r = new Random();


- Then we use two for loops to fill each index with a random number between 0 and 4, inclusive:

               for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
}
}


Note: Recall that tilemap[i][j] refers to the spot with coordinates (i, j) inside the 2D array. 
Refer to this simplified illustration if you are confused!
Here's what the code will look like as of now:

FIGURE 2-36: Renderer Class, createTilemap()

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class Renderer extends Applet {

static int[][] tilemap;
static int rows, columns;

@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
createTilemap();
}

private void createTilemap() {

tilemap = new int[50][30];


rows = tilemap.length;
columns = tilemap[49].length;


Random r = new Random();


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
}
}
}

@Override
public void paint(Graphics g) {

}

}
With the tilemap created, we can now paint it to the screen!

Lesson #2-29: Painting the Tilemap
This is what we are trying to accomplish:

1. Create a square with side length 16 pixels - 50 across and 30 down (800 x 480).
2. Give this square a random color based on the integer value (0 to 4, inclusive) inside the tilemap.

- We begin Scroll to the paint(Graphics g) method. - Add the following code inside the method:


for (int i = 0; i < rows; i++) {
   for (int j = 0; j < columns; 
   
   }
}


This is the same nested for loop we saw in the createTilemap() method. We will use i and j to refer to locations in the 2D Array.

We want to translate this (i, j) location into a coordinate system of (16*i, 16*j), because we want to represent, for example, (50, 30), as (800, 480).

So within the inner for loop, we add the following in BOLD:

for (int i = 0; i < rows; i++) {
   for (int j = 0; j < columns;
      int mod_i = 16*i;
      int mod_j = 16*j;
   }
}

Note: The underscore "_" does not have any meaning. It is just part of the variable names, which stand for modified I and modified J.

Now directly below the two variable declarations (and still within the inner for loop), we need to create a switch that takes tilemap[i][j] as the key (recall that switches are used to compare the value of a key against cases) and compare with the integers 0 through 4, inclusive.

For each case, we will set the color of g, which needs to be set directly before you paint an object, and then paint a rectangle on the screen at the coordinates (mod_i, mod_j).

The full class will now look like this:

FIGURE 2-37: RENDERER CLASS, Completed

import java.applet.Applet;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.util.Random;

public class Renderer2 extends Applet {

static int[][] tilemap;
static int rows, columns;

@Override
public void init() {
setSize(800, 480);
setBackground(Color.BLACK);
createTilemap();

}

@Override
public void paint(Graphics g) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {

int mod_i = 16*i;
int mod_j = 16*j;

switch (tilemap[i][j]) {
case 0:
g.setColor(Color.RED);
g.fillRect(mod_i, mod_j, 16, 16);
break;
case 1:
g.setColor(Color.BLUE);
g.fillRect(mod_i, mod_j, 16, 16);
break;
case 2:
g.setColor(Color.YELLOW);
g.fillRect(mod_i, mod_j, 16, 16);
break;
case 3:
g.setColor(Color.WHITE);
g.fillRect(mod_i, mod_j, 16, 16);
break;
case 4:
g.setColor(Color.GREEN);
g.fillRect(mod_i, mod_j, 16, 16);
break;

}

}

}

}

private void createTilemap() {

tilemap = new int[50][30];

rows = tilemap.length;
columns = tilemap[49].length;


Random r = new Random();

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
}
}
}

}
Now press Play! You should see a beautiful painting like this:

And with that, our mini-break from 2D game development (Days 9 and 10) is over, and so concludes Unit 2!

In the next lessons, we will be applying these techniques to create our levels, and eventually introduce collision detection.

I hope that this lesson made sense to everyone! I know that everyone is at different levels of Java experience and understanding, and I try to find a good balance as to not bore people and to not leave people behind. I might assume that you remember something from a previous lesson, but you might have forgotten it already. So let me know if you need anything better explained. I'd be glad to do that for you.

GAME DEVELOPMENT TUTORIAL: DAY 2-9: Two-Dimensional Arrays

Welcome to Day 9! Today's lesson will be short, but full of information. We are building towards loading pre-made Level designs and rendering tiles to the screen. To do so, we must first go over some basic fundamentals. Therefore, we will be creating a new project to practice and study these new topics!
Lesson #2-26: Arrays
One of the most powerful tools in a programmer's arsenal is the array. You can think of an array as a list of items. Let's say you had three favorite things:

1. Playing
2. Eating
3. Sleeping

These three things could easily be categorized into one list so that you can refer people to this list rather than three separate variables. That's what an array does, in principle.

1. To see this in action, create a new Project, and name it whatever you want.
2. Within the src folder, create a new Java class called: Array.
3. Add the main method:

  public static void main(String args[]) {

}

4. Within the main method, declare the following:

String[] favoriteThings = new String [3];


This creates an Array (list) of String objects called stringArray, and allocates memory to accommodate three (3) items.

Alternatively, this same line can be written as below, by shifting the brackets:
String favoriteThings[] = new String [3];

Astute observers will recognize this syntax. If you examine the parameter of the main method:
String args[], you will now see that the main method takes in an array of Strings as a parameter. These arrays are passed in at a lower level, and you will not encounter them in Eclipse.

Your code should be looking like this:

Figure 2-34: Array Class

 public class Array {

         public static void main(String args[]) {
String[] favoriteThings = new String [3];
}

}
Now let's talk about how to fill this Array.

We can refer to positions in the array as indices. The first item in the list will have an index of 0, the second will have 1, and so on.

To refer to a specific index of an Array, we can write:
array[index].

Going back to our code, we can list our three favorite things as follows:

...
public static void main(String args[]) {
String[] favoriteThings = new String [3];

favoriteThings[0] = "Playing";
favoriteThings[1] = "Eating";
favoriteThings[2] = "Sleeping";

}
...

What if we now want to print all these items?
It's tempting to use System.out.println(favoriteThings), but this will return what seems to be nonsense.

Instead, we must use a for loop, and iterate over an index to print each line.

This is how I would approach it:

for (int i = 0; i < favoriteThings.length; i++) {
System.out.print(i+1 + ". ");
System.out.println(favoriteThings[i]);
}


This code introduces nothing new. It is just application of previously-covered topics. Make sure you understand this before moving on!

If we place this for loop at the bottom of the main method, we will see the following output:
Understand how it works? Then you are ready for the next level.
Lesson #2-27: Two-Dimensional Arrays
The most practical application of a two-dimensional Array is when you need to store a list of values with (x, y) positions.

For our game's purposes, we will use a 2D array to hold a value at each position, and then paint the object/character/platform associated with said value at its (x, y) coordinate.


2D Arrays are very similar to single dimensional arrays, but we add a second dimension (like adding a width).

Two create a 2D array, we simply state:
int[][] intArray = new int[30][50]; //Creates a 2D array of integers with height 30 and width 50.

1. Create a new class called Tilemap.
2. Add the following code:

Figure 2-35: Tilemap Class

import java.util.Random;

public class Tilemap {


public static void main(String args[]) {
Tilemap tp = new Tilemap();

}

public Tilemap() {
int[][] tilemap = new int[30][50];

System.out.println("New Tilemap created.");
Random r = new Random();

int rows = tilemap.length;
int columns = tilemap[1].length;

printTiles(rows, columns, tilemap, r);

}

private void printTiles(int rows, int columns, int[][] tilemap, Random r) {

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
tilemap[i][j] = r.nextInt(5);
System.out.print(" " + tilemap[i][j]);
}

System.out.println("");

}
}

}
Before you run this code, let's talk about what each segment of code does.

1. We import the Random class (to be used later)
2. In the main method, we create a new Tilemap object called tp. This calls the constructor below the main method.

3. In the constructor, we create a new two dimensional array called tilemap, with height 30, and width 50.
- We also create a Random object called r

Two-dimensional arrays can be thought of as Arrays of Arrays. Meaning that it is a list of lists. The larger list has 30 empty spots. Each of those 30 spots has 50 spots across.

Therefore, when we refer to tilemap.length, we get the length of the larger list, which is 30.
When we refer to tilemap[1].length, we get the length of the small list with index 1 in the large list, which is the second small list in the large list. This will have a value of 50.

4. We then call the printTiles() method, which takes in various parameters, uses two for loops (one for the columns and another for the rows).

This printTiles() method gives each space a value between 0 to 4 (at random). Then we print each row and column.

The result should look something like this:
In the next lesson, we will associate each integer from 0 to 4 with a colored rectangle and fill the screen. This will then segue into a Unit 3, beginning with a series of lessons on Level design/rendering and collision physics!

Stay Tuned!