Saturday, 30 June 2012

Android Removeing Title bar in Manifest


 Application level removing the Title bar

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mmad.salesapp"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="14" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen" >
        <activity
            android:label="@string/app_name"
            android:name=".Login"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="TabSelection"></activity>
  </manifest>


Activity Level removing the Title Bar

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mmad.salesapp"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="14" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
       >
        <activity
            android:label="@string/app_name"
            android:name=".Login"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="TabSelection"
          android:theme="@android:style/Theme.Holo.NoActionBar.Fullscreen"></activity>
  </manifest>


Friday, 29 June 2012

Android set the values at listview from database using bean

package com.mmad.sales;

import java.util.ArrayList;
import java.util.List;

import com.mmad.sales.CopyOfDailyReport.ViewHolder;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class DailyReport extends Activity {
    ListView lv;
    LocationAdapter locationAdapter;
    List<String> day;
    List<BeanOutlet> outletList;
    Helper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.daily_report);

        lv = (ListView) findViewById(R.id.listView1);
        helper = new Helper(getApplicationContext());
        dailyReport();
    }

    private void dailyReport() {
       
        outletList = helper.getOutlet();
        locationAdapter = new LocationAdapter(this);
        lv.setAdapter(locationAdapter);
        locationAdapter.setNotifyOnChange(true);
        locationAdapter.notifyDataSetChanged();
    }

    public class ViewHolder {
        TextView dayName;
        TextView nameOfOutlet;
    }

    public class LocationAdapter extends ArrayAdapter {
        Context context;

        public LocationAdapter(Context context) {
            super(context, R.layout.daily_report_details, outletList);
            this.context = context;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = (LinearLayout) LayoutInflater.from(context)
                        .inflate(R.layout.daily_report_details, null);
                holder = new ViewHolder();
                holder.dayName = (TextView) convertView
                        .findViewById(R.id.textView1);
                holder.nameOfOutlet = (TextView) convertView
                        .findViewById(R.id.textView2);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();

            }

            // holder.dayName.setText(day.get(position));

            holder.dayName.setText(outletList.get(position).getOutletCity());
            holder.nameOfOutlet.setText(outletList.get(position)
                    .getOutletName());

            return convertView;
        }

    }

}

Android set values staticaly in list view using viewholder method

package com.mmad.sales;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class CopyOfDailyReport extends Activity {
    ListView lv;
    LocationAdapter locationAdapter;
    List<String> day;
    List<BeanOutlet> outletList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.daily_report);
       
        lv=(ListView)findViewById(R.id.listView1);
       
        dailyReport();
    }

    private void dailyReport() {
   
         day=new ArrayList<String>();
       
        day.add("Sunday");
        day.add("Monday");
        day.add("TusDay");
        day.add("Wednesday");
        day.add("Thourday");
        day.add("Friday");
        day.add("Saturday");
       
       
         locationAdapter = new LocationAdapter(this);
         lv.setAdapter(locationAdapter);
         locationAdapter.setNotifyOnChange(true);
         locationAdapter.notifyDataSetChanged();
    }
   
    public class ViewHolder
    {
        TextView textiew;
    }
   
   
    public class LocationAdapter extends ArrayAdapter {
          Context context;
         
          public LocationAdapter(Context context) {
           super(context, R.layout.daily_report_details,day);
           this.context = context;
          
          }
         
          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
           ViewHolder holder;
           if(convertView == null) { 
            convertView = (LinearLayout)LayoutInflater.from(context).inflate(R.layout.daily_report_details, null);
            holder =  new ViewHolder();
            holder.textiew=(TextView)convertView.findViewById(R.id.textView1);
          
           
            convertView.setTag(holder);
           }
           else{
            holder = (ViewHolder) convertView.getTag();
           }
       
          holder.textiew.setText(day.get(position));

       
          
   
           return convertView;
          }
         
         }
       
   

}

Tuesday, 26 June 2012

Passing a Bundle on Activity


1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
 
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
 
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value); 
 
 
Getting Value in naother activity
 
Bundle bundle = this.getIntent().getExtras();  
if(bundle !=null) {
  String strdata = bundle.getString("senddata");
}
 

Friday, 22 June 2012

Using Google Maps in Android

http://mobiforge.com/developing/story/using-google-maps-android

 ************************************************************
my API key what i followed

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\balaji>Cd Program Files\Java\jdk1.6.0_21\bin
The system cannot find the path specified.

C:\Users\balaji>cd\

C:\>cd C:\Program Files\Java\jdk1.6.0_21\bin

C:\Program Files\Java\jdk1.6.0_21\bin>keytool.exe -v -list  -alias androiddebugk
ey -keystore "C:\android\debug.keystore" -storepass android -keypass android
keytool error: java.lang.Exception: Keystore file does not exist: C:\android\deb
ug.keystore
java.lang.Exception: Keystore file does not exist: C:\android\debug.keystore
        at sun.security.tools.KeyTool.doCommands(KeyTool.java:569)
        at sun.security.tools.KeyTool.run(KeyTool.java:172)
        at sun.security.tools.KeyTool.main(KeyTool.java:166)

C:\Program Files\Java\jdk1.6.0_21\bin>keytool.exe -v -list  -alias androiddebugk
ey -keystore "C:\Users\balaji\.android\debug.keystore" -storepass android -keypa
ss android
Alias name: androiddebugkey
Creation date: 21 May, 2012
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 4fba250f
Valid from: Mon May 21 16:50:47 IST 2012 until: Wed May 14 16:50:47 IST 2042
Certificate fingerprints:
         MD5:  75:61:5A:5A:14:4B:E6:77:2B:95:79:7E:FE:8F:7C:9D
         SHA1: 46:0F:AB:FF:BF:4C:8D:0D:8A:D9:6F:FD:BE:D4:04:8B:A9:E8:66:97
         Signature algorithm name: SHA1withRSA
         Version: 3

C:\Program Files\Java\jdk1.6.0_21\bin>
*****************************************************************

if error comes like dot


http://mirnauman.wordpress.com/2012/01/30/using-google-maps-in-android-development-tutorial-part-1/

Wednesday, 20 June 2012

Android Tab Layout Tutorial


In my previous article Android Layouts i explained about three layouts (Linear Layout, Relative Layout and Table Layout). In this post i will be discussing about Android Tab Layout. This is a simple tab layout contains 3 tabs.
Download Code

The final output of this tutorial will be like below image
Android Tab Layout output

In this post we need three separate activities for three tab screens. So let’s get started by creating a simple project by opening eclipse IDE.

1. Create a new project File -> New -> Android Project and give activity name as AndroidTabLayoutActivity.
2. Open your AndroidTabLayoutActivity and extend the class from TabActivity.
public class AndroidTabLayoutActivity extends TabActivity {

3. Now open your main.xml under res -> layout folder and type the following code.
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    </LinearLayout>
</TabHost>

4. Now we need 3 activities and 3 xml layouts for three tabs. So create three activities by right click on your package folder and create classes and name them as PhotosActivity.java, SongsActivity.java and VideosActivity.java. Type the following code respectively.
Right Click on package folder -> New -> Class
» PhotosActivity.java
package com.example.androidtablayout;

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

public class PhotosActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos_layout);
    }
}
» SongsActivity.java
package com.example.androidtablayout;

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

public class SongsActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.songs_layout);
    }
}
» VideosActivity.java
package com.example.androidtablayout;

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

public class VideosActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videos_layout);
    }
}

5. Now create 3 xml layouts by right clicking on res/layout -> New -> Android XML File and name them as photos_layout.xml, songs_layout.xml and videos_layout.xml and type the following code in respective files.
» photos_layout.xml
<?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">

  <!-- Screen Design for Photos -->
  <TextView android:text="PHOTOS HERE"
            android:padding="15dip"
            android:textSize="18dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

</LinearLayout>
» songs_layout.xml
<?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">

  <!-- Screen Design for the SONGS -->
  <TextView android:text="SONGS HERE"
            android:padding="15dip"
            android:textSize="18dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>
» videos_layout.xml
<?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">

  <!--  Screen Design for VIDEOS -->
  <TextView android:text="VIDEOS HERE"
            android:padding="15dip"
            android:textSize="18dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>

6. Each and every tab needs an icon so design icons for each tab. We need three dimensions of each icon. Design each icon in 48 x 48 px, 32 x 32 px and 24 x 24 px and place them in drawable-hdpi, drawable-mdpi and drawable-ldpi respectively. See following diagram for your guidance
Android icon sizes

7. Android icon states will be define in xml files with default and hover state configurations. For three icons we need the icon state configuration files. So create three 3 xml files under drawable-hdpi directory. Type the following code for icon states.
» icon_photos_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/photos_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/photos_white" />
</selector>
» icon_songs_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/songs_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/songs_white" />
</selector>
» icon_videos_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/videos_gray"
          android:state_selected="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/videos_white" />
</selector>

8. Now open AndroidTabLayoutActivity.java and type the following code. In the following code we are creating three TabSepcs and adding them to TabHost.
» AndroidTabLayoutActivity.java
package com.example.androidtablayout;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

public class AndroidTabLayoutActivity extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TabHost tabHost = getTabHost();

        // Tab for Photos
        TabSpec photospec = tabHost.newTabSpec("Photos");
        // setting Title and Icon for the Tab
        photospec.setIndicator("Photos", getResources().getDrawable(R.drawable.icon_photos_tab));
        Intent photosIntent = new Intent(this, PhotosActivity.class);
        photospec.setContent(photosIntent);

        // Tab for Songs
        TabSpec songspec = tabHost.newTabSpec("Songs");
        songspec.setIndicator("Songs", getResources().getDrawable(R.drawable.icon_songs_tab));
        Intent songsIntent = new Intent(this, SongsActivity.class);
        songspec.setContent(songsIntent);

        // Tab for Videos
        TabSpec videospec = tabHost.newTabSpec("Videos");
        videospec.setIndicator("Videos", getResources().getDrawable(R.drawable.icon_videos_tab));
        Intent videosIntent = new Intent(this, VideosActivity.class);
        videospec.setContent(videosIntent);

        // Adding all TabSpec to TabHost
        tabHost.addTab(photospec); // Adding photos tab
        tabHost.addTab(songspec); // Adding songs tab
        tabHost.addTab(videospec); // Adding videos tab
    }
}

9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below
» AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.androidtablayout"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

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

        <!--  Songs Activity -->
        <activity android:name=".SongsActivity" />

        <!--  Videos Activity -->
        <activity android:name=".VideosActivity" />

        <!--  Photos Activity -->
        <activity android:name=".PhotosActivity" />

    </application>
</manifest>

10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You will see simple tabs app with awesome navigation.

Android Layouts: Linear Layout, Relative Layout and Table Layout


In this post I will be discussing about the different view layouts in an android mobile application. The six different layouts are

1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View
Download Code

Android allows you to create view layouts using simple XML file (we can also create a layout using java code). All the layouts must be placed in /res/layout folder.
Android Layout Directory

Okay, now lets get started with the view layouts.



1. Linear Layout

In a linear layout, like the name suggests, all the elements are displayed in a linear fashion(below is an example of the linear layouts), either Horizontally or Vertically and this behavior is set in android:orientation which is an attribute of the node LinearLayout.

Example of Vertical layout snippet
<LinearLayout android:orientation="vertical"> .... </LinearLayout>

Example of Horizontal layout snippet
<LinearLayout android:orientation="horizontal"> .... </LinearLayout>
Android Layout

Now that we know the two types of linear layouts, here are the steps you need to follow to create them

1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “linear_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “linear_layout.xml”) and type the following code.
<?xml version="1.0" encoding="utf-8"?>
<!-- Parent linear layout with vertical orientation -->
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="Email:" android:padding="5dip"/>

  <EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>          

  <Button android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="Login"/>

  <!-- Child linear layout with horizontal orientation -->
  <LinearLayout android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
              android:orientation="horizontal" android:background="#2a2a2a"
              android:layout_marginTop="25dip">

  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
         android:text="Home" android:padding="15dip" android:layout_weight="1"
         android:gravity="center"/>

  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
         android:text="About" android:padding="15dip" android:layout_weight="1"
         android:gravity="center"/>

  </LinearLayout>

</LinearLayout>

4. To set this newly created view as the initial view of your app, Open your MainActivity.java file. You would see the following line inside the onCreate function setContentView(R.layout.main). Change R.layout.main to R.layout.yourlinearviewname. In my case its R.layout.linear_layout
package com.example.androidlayouts;
import android.app.Activity;
import android.os.Bundle;

public class AndroidLayoutsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linear_layout);
    }
}

5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created linear layout in the emulator.
Linear layout output


2. Relative Layout

In a relative layout every element arranges itself relative to other elements or a parent element.
As an example, lets consider the layout defined below. The “Cancel” button is placed relatively, to the right of the “Login” button parallely. Here is the code snippet that achieves the mentioned alignment (Right of Login button parallely)

Example code snippet
<Button android:id="@+id/btnLogin" ..></Button>

<Button android:layout_toRightOf="@id/btnLogin"
            android:layout_alignTop="@id/btnLogin" ..></Button>
Android relative layout

Here are the steps to create a relative layout

1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “relative_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “relative_layout.xml”) and type the following code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

    <TextView android:id="@+id/label" android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:text="Email" />

    <EditText android:id="@+id/inputEmail" android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:layout_below="@id/label" />

    <Button android:id="@+id/btnLogin" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_below="@id/inputEmail"
            android:layout_alignParentLeft="true" android:layout_marginRight="10px"
            android:text="Login" />

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btnLogin"
            android:layout_alignTop="@id/btnLogin"  android:text="Cancel" />

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" android:text="Register new Account"
            android:layout_centerHorizontal="true"/>
</RelativeLayout>

4. Same like before open your MainActivity.java file and set the layout to your newly created relative layout file. In my case its R.layout.relative_layout
setContentView(R.layout.relative_layout);

5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created relative layout in the emulator.
Relative layout output


3. Table Layout

Table layouts in Android works in the same way HTML table layouts work. You can divide your layouts into rows and columns. Its very easy to understand. The image below should give you an idea.
Table layout

1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “table_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “table_layout.xml”) and type the following code.
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:shrinkColumns="*"  android:stretchColumns="*" android:background="#ffffff">
    <!-- Row 1 with single column -->
    <TableRow
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:gravity="center_horizontal">
        <TextView
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:textSize="18dp" android:text="Row 1"  android:layout_span="3"
            android:padding="18dip" android:background="#b0b0b0"
            android:textColor="#000"/>
    </TableRow>

    <!-- Row 2 with 3 columns -->
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
        <TextView
            android:id="@+id/TextView04" android:text="Row 2 column 1"
            android:layout_weight="1" android:background="#dcdcdc"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
        <TextView
            android:id="@+id/TextView04" android:text="Row 2 column 2"
            android:layout_weight="1" android:background="#d3d3d3"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
        <TextView
            android:id="@+id/TextView04" android:text="Row 2 column 3"
            android:layout_weight="1" android:background="#cac9c9"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
    </TableRow>

    <!-- Row 3 with 2 columns -->
    <TableRow
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:gravity="center_horizontal">
        <TextView
            android:id="@+id/TextView04" android:text="Row 3 column 1"
            android:layout_weight="1" android:background="#b0b0b0"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>

        <TextView
            android:id="@+id/TextView04" android:text="Row 3 column 2"
            android:layout_weight="1" android:background="#a09f9f"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
    </TableRow>

</TableLayout>

4. Same like before open your MainActivity.java file and set the layout to your newly created table layout file. In my case its R.layout.table_layout
setContentView(R.layout.table_layout);

5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created table layout in the emulator.
table layout output

I have just discussed Linear Layout, Relative Layout and Table Layout in this post. The remaining Grid View, Tab Layout and List View will be covered in the next article. Stay tuned!

How to switch between Activities in Android

In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.
Download Code
Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java
Opening new Activity
To open new activity following startActivity() or startActivityForResult() method will be used.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

Sending parameters to new Activity
To send parameter to newly created activity putExtra() methos will be used.
i.putExtra("key", "value");
 
// Example of sending email to next screen as
// Key = 'email'
// value = 'myemail@gmail.com'
i.putExtra("email", "myemail@gmail.com");

Receiving parameters on new Activity
To receive parameters on newly created activity getStringExtra() method will be used.
Intent i = getIntent();
i.getStringExtra("key");
 
// Example of receiving parameter having key value as 'email'
// and storing the value in a variable named myemail
String myemail = i.getStringExtra("email");

Opening new Activity and expecting result
In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 100); // 100 is some code to identify the returning result
 
// Function to read the result from newly created activity
@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
 
             // Storing result in a variable called myvar
             // get("website") 'website' is the key value result data
             String mywebsite = data.getExtras().get("result");
        }
 
    }

Sending result back to old activity when StartActivityForResult() is used
Intent i = new Intent();
// Sending param key as 'website' and value as 'androidhive.info'
i.putExtra("website", "AndroidHive.info");
 
// Setting resultCode to 100 to identify on old activity
setResult(100,in);

Closing Activity
To close activity call finish() method
finish();

Add entry in AndroidManifest.xml
To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between <application> tags
<activity android:name=".NewActivityClassName"></activity>

Let’s Start with a simple project
So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java, SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.
Directory Structure
Now lets start by creating a simple project.
1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java
3. Create a new xml file in layout folder or rename the main.xml to screen1.xml
Right Click on Layout -> New -> Android XML file and name it as screen1.xml
4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.
<?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"
    >
    <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Name: "/>
    <EditText android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email: "
        />
    <EditText android:id="@+id/email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>
    <Button android:id="@+id/btnNextScreen"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Send to Next Screen"
            android:layout_marginTop="15dip"/>
</LinearLayout>
Screen1.xml output
5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.
package com.example.androidswitchviews;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
 
public class FirstScreenActivity extends Activity {
    // Initializing variables
    EditText inputName;
    EditText inputEmail;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);
 
        inputName = (EditText) findViewById(R.id.name);
        inputEmail = (EditText) findViewById(R.id.email);
        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
 
        //Listening to button event
        btnNextScreen.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View arg0) {
                //Starting a new Intent
                Intent nextScreen = new Intent(getApplicationContext(), SecondScreenActivity.class);
 
                //Sending data to another Activity
                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("email", inputEmail.getText().toString());
 
                Log.e("n", inputName.getText()+"."+ inputEmail.getText());
 
                startActivity(nextScreen);
 
            }
        });
    }
}
6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java
Android creating new class
7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
 
  <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="You Entered..."
            android:textSize="25dip"
            android:gravity="center"
            android:layout_margin="15dip"/>
 
  <TextView android:id="@+id/txtName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dip"
            android:textSize="18dip"/>
 
  <TextView android:id="@+id/txtEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dip"
            android:textSize="18dip"/>
 
  <Button android:id="@+id/btnClose"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dip"
            android:text="Close"/>
 
</LinearLayout>
8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen
package com.example.androidswitchviews;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
public class SecondScreenActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);
 
        TextView txtName = (TextView) findViewById(R.id.txtName);
        TextView txtEmail = (TextView) findViewById(R.id.txtEmail);
        Button btnClose = (Button) findViewById(R.id.btnClose);
 
        Intent i = getIntent();
        // Receiving the Data
        String name = i.getStringExtra("name");
        String email = i.getStringExtra("email");
        Log.e("Second Screen", name + "." + email);
 
        // Displaying Received data
        txtName.setText(name);
        txtEmail.setText(email);
 
        // Binding Click event to Button
        btnClose.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View arg0) {
                //Closing SecondScreen Activity
                finish();
            }
        });
 
    }
}
9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below
<?xml version="1.0" encoding="utf-8"?>
      package="com.example.androidswitchviews"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk android:minSdkVersion="8" />
 
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".FirstScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Add new Activity class name here --->
        <activity android:name=".SecondScreen"></activity>
 
    </application>
</manifest>
10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens. The below image is output screenshots of both xml files.
Switching between views in Android Output