Sunday, 21 December 2014

Android Application Development using Android Studio: Tab Based Application

If you are looking for creating a tab based android application using Android Studio, I would say you reached to right post. In this post I will be showing how you can create tab based android application. Also, you can watch this video to get more detail on the application that I will walk you through in this post.




Application Requirement
First of all I would like to describe the application requirement. I just thought to create a simple application which can be used to maintain daily expenses. I would call it ‘Expense Book’ and this application can be used to add your expenses in terms of transactions and view the list of created transactions.  Below image describes requirement very well than my word.


Environment Setup
To develop this application, Android Studio is used. Before creating this application you should ensure to have following software installed:
  • JDK 7
  • Android SDK
  • Android Studio 1.0.1


If you have not installed these tools, you can refer my post to install it from scratch. 

How to develop above application?




1. Open Android Studio and go to ‘File > New Project…’ and click on ‘Next’ by following default options and finish. 

2. Create layout files (.xml) which are shown as selected in below image:


tab.xml

This xml is the layout of tab bar.

<?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 Food tab -->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView" />
</LinearLayout>

If you open this xml in android studio and go to 'design' tab, you will see below layout.


addtransactiontab.xml

This xml is the layout of first tab. All text fields and action button is added in this layout.

<?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 Food tab -->
    <FrameLayout android:id="@android:id/tabcontent"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <LinearLayout
            android:id="@+id/tab1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:clickable="true"
            android:background="@drawable/bg_loading_320">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Add Transaction"
                android:id="@+id/addTransactionView"
                android:layout_centerHorizontal="true"
                android:layout_alignParentTop="true"
                android:textSize="25dp"
                android:singleLine="false"
                android:textColor="#ffff9408" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:ems="10"
                android:id="@+id/txtTransactionName"
                android:layout_marginTop="34dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:hint="Transaction Name" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="date"
                android:ems="10"
                android:id="@+id/txtTransactionDate"
                android:hint="Date - DD/MM/YYYY " />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:ems="10"
                android:id="@+id/txtAmount"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
               android:hint="Amount" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/txtPayee"
                android:hint="Payee" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:id="@+id/txtTransactionDetial"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:hint="Transaction Detail"
                android:singleLine="false" />

            <Button
                android:layout_width="237dp"
                android:layout_height="52dp"
                android:text="Add Transaction"
                android:id="@+id/btnAdd"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="27dp"
                android:enabled="false"
                android:background="#ffffa00f"
                android:layout_gravity="center_horizontal"
                android:textSize="25dp" />
        </LinearLayout>
    </FrameLayout>
</LinearLayout>

If you open this xml in android studio and go to 'design' tab, you will see below layout.



 listtransactiontab.xml

This xml is the layout of second tab. List view is added to see the list of added transactions.

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

<TabHost android:layout_width="fill_parent"
               android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
               android:id="@android:id/tabhost">
               <LinearLayout android:id="@+id/LinearLayout01"
                              android:orientation="vertical" android:layout_height="fill_parent"
                              android:layout_width="fill_parent">
                              <TabWidget android:id="@android:id/tabs"
                                             android:layout_height="wrap_content"      
                                                    android:layout_width="fill_parent"></TabWidget>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
               </LinearLayout>

</TabHost>




3. Implement activity classes to render layout and perform action. 
  
TabBar.java

First of all you need to create 'TabActivity', This class is responsible to add required tabs when application is opened.This is the first activity that is executed when application is run.

package com.nverm.expensebook.activity;

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

import com.nverm.expensebook.R;

public class TabBar extends TabActivity {
    /** This method is called when the activity is first created. */
    
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       // This is the tab.xml view
        setContentView(R.layout.tab);
       
        /* TabHost will have Tabs */
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
       
        /* If you want to create new tab, you can use newTabSpec() on TabHost.*/
        /* addTransTabId1 is addTransactionTabSpec Id. This can be used to access outside. */
        /* addTransTabId1 is listTransTabId1 Id. This can be used to access outside. */
       
       TabSpec addTransactionTabSpec = tabHost.newTabSpec("addTransTabId1");
        TabSpec listTransactionTabSpec = tabHost.newTabSpec("listTransTabId1");
        
        /* Using setIndicator() of TabSpec you can set name for the tab which is displayed on UI */
        /* Using setContent() you can set content for a particular tab. */
       
        addTransactionTabSpec.setIndicator("Add Transaction").setContent(new 
                                Intent(this,AddTransactionTab.class));
        listTransactionTabSpec.setIndicator("Transaction List").setContent(new 
                                 Intent(this,TransactionListTab.class));

        /* Add tabSpec to the TabHost to display. */
        tabHost.addTab(addTransactionTabSpec);
        tabHost.addTab(listTransactionTabSpec);
       
    }
}
  
 AddTransactionTab.java

 This class is responsible to fetch added transaction detail on click of 'Add Transaction' button and saving into list.

public class AddTransactionTab extends Activity {
    
    // This list is used to store added transactions
    static List<Transaction> transactionList = new ArrayList<Transaction>();

    EditText tranNameTxt, tranDateTxt, amountTxt, payeeTxt, transactionDetailTxt;
  
  @Override
    protected void onCreate(Bundle instance) {
        super.onCreate(instance);
      
       // This is the addtransactiontab.xml view
        setContentView(R.layout.addtransactiontab);

        // Fetch filled text values into local variables
        tranNameTxt = (EditText) findViewById(R.id.txtTransactionName);
        amountTxt = (EditText) findViewById(R.id.txtAmount);
        payeeTxt = (EditText) findViewById(R.id.txtPayee);
        tranDateTxt = (EditText) findViewById(R.id.txtTransactionDate);
        transactionDetailTxt = (EditText) findViewById(R.id.txtTransactionDetial);

        final Button addButton = (Button) findViewById(R.id.btnAdd);

        // On click of  button, save transaction into list
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Transaction transaction = new Transaction();
                transaction.setTranNameTxt(tranNameTxt.getText().toString());
                transaction.setTranDateTxt(tranDateTxt.getText().toString());
                transaction.setAmountTxt(amountTxt.getText().toString());
                transaction.setPayeeTxt(payeeTxt.getText().toString());
                transaction.setTransactionDetailTxt(transactionDetailTxt.getText().toString());
                transactionList.add(transaction);
                System.out.println("Added transaction into list:" + transactionList);

                // Show alert of adding transaction
                Toast.makeText(getApplicationContext(), 
                      "Added transaction successfully !! Enjoy !!", Toast.LENGTH_SHORT)
                        .show();
            }
        });

        // On change of name text field
            tranNameTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
           }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                addButton.setEnabled(!tranNameTxt.getText().toString().trim().equals(""));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}

  ListTransactionTab.java
 This class is responsible to show added transactions on 'Transaction List' tab.

package com.nverm.expensebook.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nverm.expensebook.R;
import com.nverma.expensebook.vo.Transaction;

public class TransactionListTab extends Activity {

    /** This method is called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
                              super.onCreate(savedInstanceState);

        // If list is empty show empty text message      
        if(AddTransactionTab.transactionList.isEmpty()){
            TextView textView = new TextView(this);
            textView.setText("\n               No transactions added yet !!!");
            setContentView(textView);
            return;
        }else{          
           // This is the listtransactiontab.xml view
            setContentView(R.layout.listtransactiontab);
        }

        final ListView listView = (ListView) findViewById(R.id.listView);

        String [] transactionNames = new String[AddTransactionTab.transactionList.size()];
        int i = -1;
        for(Transaction transaction : AddTransactionTab.transactionList){
            transactionNames[++i] = "Name:"
            + transaction.getTranNameTxt() 
            + ", Amount:" + transaction.getAmountTxt()
            + ", Date:" + transaction.getTranDateTxt();
        }

        // Define a new Adapter
        // 1 parameter - Context
        // 2 parameter - Layout for the row
        // 3 parameter - ID of the TextView to which the data is written
        // 4 parameter- the Array of data
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, transactionNames);

        // Assign adapter to ListView
        listView.setAdapter(adapter);

        // ListView Item Click Listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                //Get transaction from list from given position
                Transaction transaction = AddTransactionTab.transactionList.get(itemPosition);

                // Show detail of transaction when any list item is clicked
                Toast.makeText(getApplicationContext(),transaction.toString() ,
                              Toast.LENGTH_SHORT).show();
            }
        });
    }
}

  Transaction.java

package com.nverma.expensebook.vo;

public class Transaction {
    private String tranNameTxt, tranDateTxt, amountTxt, payeeTxt, transactionDetailTxt;;

    public String getTranNameTxt() {
        return tranNameTxt;
    }

    public void setTranNameTxt(String tranNameTxt) {
        this.tranNameTxt = tranNameTxt;
    }

    public String getTranDateTxt() {
        return tranDateTxt;
    }

    public void setTranDateTxt(String tranDateTxt) {
        this.tranDateTxt = tranDateTxt;
    }

    public String getPayeeTxt() {
        return payeeTxt;
    }

    public void setPayeeTxt(String payeeTxt) {
        this.payeeTxt = payeeTxt;
    }

    public String getAmountTxt() {
        return amountTxt;
    }

    public void setAmountTxt(String amountTxt) {
        this.amountTxt = amountTxt;
    }

    public String getTransactionDetailTxt() {
        return transactionDetailTxt;
    }

    public void setTransactionDetailTxt(String transactionDetailTxt) {
        this.transactionDetailTxt = transactionDetailTxt;
    }

    @Override
    public String toString() {
        return  "Transaction Name : " + tranNameTxt + "\n" +
                "Transaction Date : " + tranDateTxt + "\n" +
                "Amount : " + amountTxt + "\n" +
                "Payee : " + payeeTxt + "\n" +
                "Transaction Detail : " + transactionDetailTxt ;
    }
}

4. Once you created these files, you are ready to run the application now. Before running application, ensure to setup AVD (Android Virtual Device). On click of run button, you will be asked to select environment to run the application. If you setup your AVD, you can choose 'Launch Emulator' option and select your AVD.


On click of 'Ok' button emulator is initialized and opened. Once you unlock the screen you will be able to see tab based application. Now you can add transaction and see added transaction on list tab. 


I hope this post helped you out creating and understanding tab based android application. If got this helping, please feel free to share your feedback. 

! Happy Android Application Development !