Ads

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 !