Search This Blog

Sunday, August 28, 2011

How to add new java file ?

To add the Java file for the test case class, follow these steps
  1. In Eclipse, open the HelloAndroidTest project if it is not already open.
  2. Within HelloAndroidTest, expand the src/ folder and then find the package icon for com.example.helloandroid.test. Right-click on the package icon and select New > Class



The New Java Class dialog appears.
3. In the dialog, enter the following:
  • Name: "HelloAndroidTest". This becomes the name of your test class.
  • Superclass: "android.test.ActivityInstrumentationTestCase2<HelloAndroid>". The superclass is parameterized by an Activity class name. The dialog should now look like this:

  • Do not change any of the other settings. Click Finish.
  • You now have a new file HelloAndroidTest.java in the project. This file contains the class HelloAndroidTest, which extends the Activity test case class ActivityInstrumentationTestCase2<T>. You parameterize the class with HelloAndroid, which is the class name of the activity under test.
  • Open HelloAndroidTest.java. It should look like this
  •  
    package com.example.helloandroid.test;
    import android.test.ActivityInstrumentationTestCase2;
    public class HelloAndroidTest extends ActivityInstrumentationTestCase2<HelloAndroid> {
    }
     
     
  • The test case class depends on the HelloAndroid class, which is not yet imported. To import the class, add the following line just before the current import statement: 
  •  
    import com.example.helloandroid.HelloAndroid;

Debug Your Project

The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, introduce a bug into your code. Change your HelloAndroid source code to 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. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Object o = null;
        o.toString();
        setContentView(R.layout.main);
    }
}
This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this:
Press "Force Quit" to terminate the application and close the emulator window.
To find out more about the error, set a breakpoint in your source code on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello, Android from the menu to enter debug mode. Your app will restart in the emulator, but this time it will suspend when it reaches the breakpoint you set. You can then step through the code in Eclipse's Debug Perspective, just as you would for any other application.

Run the Application

The Eclipse plugin makes it easy to run your applications:

  1. Select Run > Run.
  2. Select "Android Application".
The Eclipse plugin automatically creates a new run configuration for your project and then launches the Android Emulator. Depending on your environment, the Android emulator might take several minutes to boot fully, so please be patient. When the emulator is booted, the Eclipse plugin installs your application and launches the default Activity. You should now see something like this:


The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin creates this automatically (the string is defined in the res/values/strings.xml file and referenced by your AndroidManifest.xml file). The text below the title is the actual text that you have created in the TextView object.
That concludes the basic "Hello World" tutorial, but you should continue reading for some more valuable information about developing Android applications.

Saturday, August 27, 2011

How to Create a New Android Project ?


After you've created an AVD you can move to the next step and start a new Android project in Eclipse.
  1. In Eclipse, select File > New > Project....
    If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available.)
  2. Select "Android Project" and click Next.
  3. Fill in the project details with the following values:
    • Project name: HelloAndroid
    • Build Target: Select a platform version that is equal to or lower than the target you chose for your AVD.
    • Application name: Hello, Android
    • Package name: com.example.helloandroid (or your own private namespace)
    • Create Activity: HelloAndroid
    Click Finish.
    Here is a description of each field:
    Project Name
    This is the Eclipse project name — the name of the directory that contains the project files.
    Build Target
    This is the version of the Android SDK that you're using to build your application. For example, if you choose Android 2.1, your application will be compiled against the Android 2.1 platform library. The target you choose here does not have to match the target you chose for your AVD; however, the target must be equal to or lower than the target you chose for your AVD. Android applications are forward-compatible, which means an application will run on the platform against which it is built as well as all platforms that are released in the future. For example, an application that is built against the 2.1 platform library will run normally on an AVD or device that is running the 2.3.3. The reverse is not true.
    Application Name
    This is the human-readable title for your application — the name that appears on the Android device.
    Package Name
    This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity is generated.
    Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.
    Create Activity
    This is the name for the class stub that is generated by the plugin. This is a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.
    Min SDK Version
    This value specifies the minimum API Level on which your application will run. The Min SDK Version should be the same as the Build Target you chose. For example, if the Build Target is Android 2.1, then the Min SDK Version should be 7 or lower (it can never be higher than 7). For more information, see Android API Levels.
    Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files are generated and stored.

Your Android project is now ready.

How to create an AVD in eclipse ?


In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator.
To create an AVD:
  1. In Eclipse, select Window > Android SDK and AVD Manager.
  2. Select Virtual Devices in the left panel.
  3. Click New....
    The Create New AVD dialog appears.
  4. Type the name of the AVD, such as "my_avd".
  5. Choose a target.
    The target is the platform (that is, the version of the Android SDK, such as 2.3.3) you want to run on the emulator. For this tutorial, choose the latest platform that you have installed and ignore the rest of the fields.
  6. Click Create AVD.

How to add LogCat ?

Logcat is the command to view the internal logs of the Android system. Viewing logs is often the best way to diagnose a problem, and is required for many issues. This way you'll find out what apps are doing in the background without you noticing.

Advantages of Logcat

  • Debugging
  • You can see what processes are running, if a process is running after a certain interval of time, it will eat battery. So you can also find out what is draining your battery.

In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.


How do I install it?
  1. Make sure you've enabled on USB debugging on your phone in Settings -> Application -> Development
  2. 2. Get the Android SDK here: Android SDK | Android Developers
  3. Extract the SDK to any folder say C:\Android
  4. Make sure that you have installed the drivers for your phone and the operating system recognizes your phone.
Everything installed? Continuing...
Now how to actually access the log, everything in italic are commands you need to enter.

  1. Open the 'run' dialog by pressing the 'Windows' + 'r' buttons on your keyboard (minimize the browser & other non-windows programs)
  2. cmd (this will open a DOS prompt)
  3. cd c:\Android\tools (go to the directory where you extracted the SDK)
  4. adb shell
  5. Now you'll see just a '$'
  6. logcat

You can now just press the power button on your phone to see what happens. It displays everything the device is doing.

So the thing is: leave your device connected for a while and see what is actually going on when you're not using it.

Create application to display log of various lifecycle events of Android Activity. Please make at least three activities

                main.xml                              second.xml                                    setting.xml



main.xml (code)



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <TextView
            android:id="@+id/uname"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/Uname">
      </TextView>
      <EditText
            android:id="@+id/utextbox"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
      </EditText>
    </LinearLayout>
    <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">
      <TextView
            android:id="@+id/pass"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:text="@string/Pass">
      </TextView>
      <EditText
            android:id="@+id/ptextbox"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:password="true">
      </EditText>
    </LinearLayout>
    <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:gravity="center">
      <Button
            android:id="@+id/login"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="@string/Login">
      </Button>
      <Button
            android:id="@+id/clear"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:text="@string/Clear">
      </Button>
    </LinearLayout>
   
</LinearLayout>


second.xml (code)



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/mainLayout"
  android:gravity="center">
      <TextView
             android:id="@+id/welcomeNote"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Welcome !!"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:gravity="center">
</TextView>
      <Button
            android:id="@+id/setting"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:text="@string/setting"
            android:textSize="20dp"
            android:gravity="center">
</Button>
     
</LinearLayout>

setting.xml (code)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:gravity="center">
    <TextView
      android:layout_width="wrap_content"
      android:text="@string/msg"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceLarge"
      android:id="@+id/cs"
      android:textSize="30dp"
      android:gravity="center"
      android:textColor="@color/yellow">
    </TextView>    
</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string name="hello">Hello World, Ex1Activity!</string>
    <string name="app_name">Ex1</string>
    <string name="Uname">User Name : </string>
    <string name="Pass">Password : </string>
    <string name="Login">Login</string>
    <string name="Clear">Clear</string>
    <string name="WelcomeNote">Welcome </string>
    <string name="setting">Setting</string>
    <string name="msg">Coming Soon...</string>
</resources>




color.xml (How to add new xml file ?)


<?xml version="1.0" encoding="UTF-8"?>
<resources>
        <color name="yellow">#FFFF00</color>      
</resources>

Ex1Activity.java



package com.exc.first;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Ex1Activity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
      //read component from xml file
        Button login = (Button)findViewById(R.id.login);
       
      /**
       * set OnClickListener on button
       * so that code which is in between { } is run on click on login button
       */
        login.setOnClickListener(new OnClickListener() {
                 
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                       
                        /**
                         * make Intent to call other activity
                         * here Ex1Activity.this to go second.class
                         * on click login button
                         */
                        Intent SecAct = new Intent(Ex1Activity.this,second.class);
                       
                        //start second activity
                        startActivity(SecAct);
                       
                  }
            });
       
       
    }
    @Override
      protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            /**
             * it show massage on LogCat when Activity starts
             */
            Log.i("Login Activity", "Start");
      }
     
      @Override
      protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            /**
             * It show massage on LogCat when Activity OnPause
             */
            Log.i("Login Activity", "Pause");
      }
      @Override
      protected void onRestart() {
            // TODO Auto-generated method stub
            super.onRestart();
            /**
             * it show massage on LogCat when Activity onRestart
             */
            Log.i("Login Activity", "Restart");
      }
      @Override
      protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            /**
             * it show massage on LogCat when Activity OnResume
             */
            Log.i("Login Activity", "Resume");
      }
     
      @Override
      protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            /**
             * it show massage on LogCat when Activity Stop
             */
            Log.i("Login Activity", "Stop");
      }
      @Override
      protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            /**
             * it show massage on LogCat when Activity Destroys
             */
            Log.i("Login Activity", "Destroy");
      }
}


second.java (How to add new java file ? )



package com.exc.first;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class second extends Activity{

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second);
           
            //read button from xml file
            Button setting =(Button)findViewById(R.id.setting);
            setting.setOnClickListener(new OnClickListener() {
                 
                  @Override
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                       
                        Intent goToSetting = new Intent(second.this,setting.class); //go to third Activity
                        startActivity(goToSetting);                    
                  }
            });
           
      }
      @Override
      protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            /**
             * it show massage on LogCat when Activity starts
             */
            Log.i("Second Activity", "Start");
      }
     
      @Override
      protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            /**
             * it show massage on LogCat when Activity on pause
             */
            Log.i("Second Activity", "Pause");
      }
      @Override
      protected void onRestart() {
            // TODO Auto-generated method stub
            super.onRestart();
            /**
             * it show massage on LogCat when Activity Restart
             */
            Log.i("Second Activity", "Restart");
      }
      @Override
      protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            /**
             * it show massage on LogCat when Activity Resume
             */
            Log.i("Second Activity", "Resume");
      }
     
      @Override
      protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            /**
             * it show massage on LogCat when Activity  stop
             */
            Log.i("Second Activity", "Stop");
      }
      @Override
      protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            /**
             * it show massage on LogCat when Activity Destroy
             */
            Log.i("Second Activity", "Destroy");
      }

}


setting.java



package com.exc.first;

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

public class setting extends Activity {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.setting);
           
           
      }
      @Override
      protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            /**
             * it show massage on LogCat when Activity starts
             */
            Log.i("Third Activity", "Start");
      }
     
      @Override
      protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            /**
             * it show massage on LogCat when Activity Pause
             */
            Log.i("Third Activity", "Pause");
      }
      @Override
      protected void onRestart() {
            // TODO Auto-generated method stub
            super.onRestart();
            /**
             * it show massage on LogCat when Activity Restarts
             */
            Log.i("Third Activity", "Restart");
      }
      @Override
      protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            /**
             * it show massage on LogCat when Activity Resume
             */
            Log.i("Third Activity", "Resume");
      }
     
      @Override
      protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            /**
             * it show massage on LogCat when Activity stop
             */
            Log.i("Third Activity", "Stop");
      }
      @Override
      protected void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            /**
             * it show massage on LogCat when Activity Destroy
             */
            Log.i("Third Activity", "Destroy");
      }


}

and don't forget to enter entry of your new java file into manifest file

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exc.first"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Ex1Activity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".second"
                  android:label="@string/app_name">
           
        </activity>
        <activity android:name=".setting"
                  android:label="@string/app_name">
           
        </activity>

    </application>
</manifest>


Output




  • How to check LogCat ?