Wednesday, 7 March 2012

Android Default Application


First Sample Application in Android:
==========================

SampleApp
*assets
*bin
   ->classes
-->>(java classes)
   ->res
-->>(resources)
   ->classes.dex
   ->resources.ap_
   ->SampleApp.apk
*gen
   ->com
-->>sampleapp
--->>>R.java
*res
   ->drawable-hpdi
   ->drawable-lpdi
   ->drawable-mpdi
   ->layout
-->>main.xml
   ->values
-->>strings.xml
*src
   ->com
-->>sampleapp
--->>>SampleAppActivity.java
-.classpath
-.project
-AndroidManifest.xml
-progaurd.cfg
-project.properties


****************SampleAppActivity.java***********

package com.sampleapp;

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

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

*************AndroidManifest.xml*************

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sampleapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SampleAppActivity"
            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>

</manifest>

*******************main.xml*********************

Each and every component and the layout design is defined in this file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
</LinearLayout>


********************strings.xml*****************

Handles all the strings used in the project. (similar to messages.properties)

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

    <string name="hello">Hello World, SampleAppActivity!</string>
    <string name="app_name">SampleApp</string>

</resources>


***********project.properties*******************

This is a Version Control Systems.

# Project target.
target=android-7


******************progaurd.cfg******************


Android Installation


Installing Android in your system:
======================

Download  'android-sdk-windows'

Download a new eclipse of ur choice: Eclipse 3.6 and greater version

Update the eclipse by the following steps:

1. Help -> Install new software -> Install window opens

2. In Work with dropdown select -> 'ADT Plugin - https://dl-ssl.google.com/android/eclipse/ '

3. select all the checkboxes -> click 'next' -> 'finish'




--- * ---

setting adb path: (To run the apk in dos prompt)
================================

Controlpanel -> System -> Advanced -> Environment variables -> path -> edit - set the adb path
adb path ------------> C:\Softwares\android-sdk-windows\platform-tools;

 --- * ---

Android Activity Life Cycle


Activity Life Cycle:

  1. The Activity class has defined dozens of callback functions, all begin with "on".
  2. Some of them are triggered by UI events, some are lifecycle related. It isn't easy for developer to remember the usage of them.
  3. An activity has essentially four states, when some event happens, like user navigates between different activities, state transites.

1. onCreate()
2. onStart()
3. onRestart()
4. onResume()
5. onPause()
6. onStop()
7. onDestroy()




Tuesday, 6 March 2012

Android Architecture


1. Applications:

These are applications written in Java

1. Some of basic applications includes an calendar, email client, SMS program, maps, making phone calls, accessing the Web browser, accessing your contacts list and others.

2. easy for device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.

3. rest all layers are used by Google programmers, developers and hardware manufacturers.


2. Application Framework:

This is the skeleton or framework which all android developers has to follow.

    1. used to build an application
    2. to access data from other applications
    3. Resource Manager
    4. Notification Manager
    5. Activity Manager

    3. Libraries:

    1. consists of Android libraries written in C, C++, and used by various system
    2. to handle different kinds of data
    3. Some of these libraries includes  media, graphics, 3d, SQLite, web browser library etc.

    4. Runtime Android:

    1. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine.
    2. Using Dalvik, a device can run multiple VMs efficiently.
    3. The Dalvik virtual machine is a register-based virtual machine, designed and written by Dan Bornstein with contributions from other Google engineers.
    4. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.

    5. Kernel – Linux:

    “Linux kernel for underlying functionality such as threading and low-level memory management."
    Let me make it simple for you, without Linux, there is no Android. 

    Android Layouts


    Android Layouts
    -----------------
    1. An Android layout is a class.
    2. It handles to arrange the components appear on the screen.
    3. Anything that is a View can be a child of a layout.
    4. All of the layouts inherit from ViewGroup (which inherits from View) so you can nest layouts.
    5. You could also create your own custom layout by making a class that inherits from ViewGroup.
    Android supports the following ViewGroups:

    * LinearLayout
    * AbsoluteLayout
    * TableLayout
    * RelativeLayout
    * FrameLayout
    * ScrollView


    RELATIVE LAYOUT
    -----------------------


    <?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="fill_parent"
        android:layout_gravity="center_vertical"
        android:gravity="center" >

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dip"
            android:text="@string/name" />

        <EditText
            android:id="@+id/nw_name"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:layout_marginLeft="60dip"
            android:layout_toRightOf="@+id/name"
            android:text="" />

        <TextView
            android:id="@+id/degn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/name"
            android:layout_marginTop="30dip"
            android:text="@string/designation" />

        <EditText
            android:id="@+id/nw_degn"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:layout_below="@+id/nw_name"
            android:layout_marginLeft="20dip"
            android:layout_toRightOf="@+id/degn"
            android:text="" />

        <TextView
            android:id="@+id/cmpy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/degn"
            android:layout_marginTop="30dip"
            android:text="@string/company" />

        <EditText
            android:id="@+id/nw_cmpy"
            android:layout_width="100dip"
            android:layout_height="wrap_content"
            android:layout_below="@+id/nw_degn"
            android:layout_marginLeft="36dip"
            android:layout_toRightOf="@+id/cmpy"
            android:text="" />

        <Button
            android:id="@+id/btn_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/nw_name"
            android:layout_below="@+id/nw_cmpy"
            android:layout_marginTop="23dp"
            android:text="@string/next" />

        <Button
            android:id="@+id/btn_go"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/cmpy"
            android:layout_alignTop="@+id/btn_next"
            android:text="@string/go" />

    </RelativeLayout>


    TABLE LAYOUT
    -------------------


    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:orientation="vertical" >

        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center" >

            <TableRow>

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/name" />

                <EditText
                    android:id="@+id/nw_name"
                    android:layout_width="120dip"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dip"
                    android:hint="Name"
                    android:text="" />
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/degn"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/designation" />

                <EditText
                    android:id="@+id/nw_degn"
                    android:layout_width="120dip"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dip"
                    android:hint="Designation"
                    android:text="" />
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/cmpy"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/company" />

                <EditText
                    android:id="@+id/nw_cmpy"
                    android:layout_width="120dip"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dip"
                    android:hint="Company"
                    android:text="" />
            </TableRow>

            <TableRow>

                <Button
                    android:id="@+id/btn_go"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="@string/go" >
                </Button>

                <Button
                    android:id="@+id/btn_next"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:text="@string/next" >
                </Button>
            </TableRow>
        </TableLayout>

    </LinearLayout>

    Thursday, 20 October 2011

    Struts Login Application with JDBC connection


    ********Just create as Dynamic web project in eclipse and run using tomcat server*********

    1. add lib, tld  folder and web.xml, struts-config.xml inside WEB-INF
    2.index.jsp , homepage.jsp, userUnlog.jsp
    3. <%@taglib uri="/WEB-INF/tld/struts/struts-html.tld" prefix="html" %>  in welcome.jsp
    4. LoginForm, LoginAction, Loginservice, LoginServiceImpl



    Folder Structure of StrutsApplication
    LoginApplication
    *src
    ----com.action -> LoginAction.java
    ----com.form   -> LoginForm.java
    ----com.service -> LoginService.java
                     -> LoginServiceImpl.java
    *webcontent
    ----WEB-INF
    -> lib
              -->> antlr.jar, commons-beanutils, coms-digester,
               coms-fileupload, coms-logging, coms-validator,
                       jakarta-oro, jstl, ojdbc14, standard, struts.jar, struts-el.jar
    -> tld --->> struts
                 ---->>> struts-html.tld
                 ---->>> struts-logic.tld
    -> struts-config.xml
    -> web.xml
    ----homepage.jsp
    ----index.jsp
    ----userUnlog.jsp


    **********  web.xml **************

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>StrutsApplication1</display-name>

    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
    <servlet-name>actionServlet</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
    <param-name>config</param-name>
    <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
    <servlet-name>actionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <session-config>
    <session-timeout>120</session-timeout>
    </session-config>

    <jsp-config>
    <taglib>
    <taglib-uri>http://jakarta.apache.org/struts/tags-html</taglib-uri>
    <taglib-location>/WEB-INF/tld/struts/struts-html.tld</taglib-location>
    </taglib>

    <taglib>
    <taglib-uri>http://jakarta.apache.org/struts/tags-logic</taglib-uri>
    <taglib-location>/WEB-INF/tld/struts/struts-logic.tld</taglib-location>
    </taglib>
    </jsp-config>
    </web-app>

    **********  struts-config.xml **************

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- ?xml version="1.0" encoding="ISO-8859-1" ?-->

    <!DOCTYPE struts-config PUBLIC
              "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
              "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

    <struts-config>
    <form-beans>
    <form-bean name="LoginForm" type="com.form.LoginForm" />
    </form-beans>

    <action-mappings>
    <action input="/index.jsp" name="LoginForm" path="/Login"
    scope="session" type="com.action.LoginAction">
    <forward name="SUCCESS" path="/homepage.jsp" />
    <forward name="FAILURE" path="/userUnlog.jsp" />
    </action>
    </action-mappings>
    </struts-config>

    **********  LoginForm.java**************

    package com.form;
    import org.apache.struts.action.ActionForm;
    public class LoginForm extends ActionForm{
    private static final long serialVersionUID = 1L;
    String userName;
    String password;

    public String getUserName() {
    return userName;
    }
    public void setUserName(String userName) {
    this.userName = userName;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    }

    **********  LoginService.java**************

    package com.service;
    import java.util.List;
    public interface LoginService {
    public boolean userValidation(String username, String userpass);
    }


    **********  LoginServiceImpl.java**************

    package com.service;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import com.form.LoginForm;
    public class LoginServiceImpl implements LoginService {
    public boolean userValidation(String username, String userpass){

    System.out.println("Username & password : " + username + " " + userpass);
    String strQuery= "";
            boolean validUser = false;
    try {
    Class.forName("oracle.jdbc.OracleDriver");
    Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "db_username", "db_password");
    Statement statement = connection.createStatement();
    strQuery="select * from user_table where username='"+username+"' and  password='"+userpass+"'";
    System.out.println(strQuery);  

    ResultSet rs = statement.executeQuery(strQuery);
    rs = statement.executeQuery(strQuery);
    System.out.println("Result : " + rs);
                boolean more = rs.next();

                if (!more) {
                validUser = false;
          }else if (more) {
                validUser = true;
                }
    }catch (Exception ex) {
                System.out.println("Log In failed: An Exception has occurred! " + ex);
    }
    return validUser;
    }
    }

    **********  LoginAction.java**************

     package com.action;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import com.form.LoginForm;
    import com.service.LoginService;
    import com.service.LoginServiceImpl;
    public class LoginAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {

    LoginForm loginForm = (LoginForm) form;
    String username = loginForm.getUserName();
    String password = loginForm.getPassword();

    HttpSession session = request.getSession(true);
    session.setAttribute("currentSessionUser", username);

    LoginService loginService = new LoginServiceImpl();
    boolean isValidUser = loginService.userValidation(username, password);

    if (isValidUser) {
    return mapping.findForward("SUCCESS");
    } else {
    return mapping.findForward("FAILURE");
    }
    }
    }


    **********  index.jsp **************

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@taglib uri="/WEB-INF/tld/struts/struts-html.tld" prefix="html" %>

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Struts Example</title>
    </head>
    <body>
    <center>
    <html:form action="/Login" method="post">
            User Name :<html:text property="userName" /><br>
            Password  :<html:password property="password" /><br>
            <html:submit value="Login" />
        </html:form>
        </center>
    </body>
    </html>


    **********  homepage.jsp **************

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
    <title> User Logged Successfully </title>
    </head>
    <body>
    <center>
    <% String user = (String)session.getAttribute("currentSessionUser"); %>
    Welcome <%= user %> !!
    </center>
    </body>
    </html>


    **********  userUnlog.jsp **************

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Invalid user</title>
    </head>
    <body>
    <center>
    Sorry, you are not a registered user! Please sign up first..
    </center>
    </body>
    </html>

    ************************************************************************

    Simple Servlet login application with jdbc connection



    ************** index.jsp ****************

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <form action="LoginServlet">
    Please enter your username <input type="text" name="un"/><br>
    Please enter your password <input type="password" name="pw"/>
    <input type="submit" value="submit">
    </form>
    </body>
    </html>

    ***************** LoginServlet.java ******************

    package login;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
         
        public LoginServlet() {
            super();
        }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

     String username = request.getParameter("un");
     String userpass = request.getParameter("pw");
     String strQuery= "";

     try {
     Class.forName("oracle.jdbc.OracleDriver");

     Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "photonmail", "photonmail");
     Statement statement = connection.createStatement();

     strQuery="select * from user_table where username='"+username+"' and  password='"+userpass+"'";
     
     ResultSet rs = statement.executeQuery(strQuery);
     rs = statement.executeQuery(strQuery);
     System.out.println("Result : " + rs);

              boolean more = rs.next();
               // check user is valid
               if (!more) {
                   System.out.println("Sorry, you are not a registered user! Please sign up first");
                   out.println(" Sorry, register first!");
               }
               else if (more) {
                out.println("Welcome " + username);
               }

     } catch (ClassNotFoundException e) {
    e.printStackTrace();
     } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    }

    }

    ************** web.xml ****************

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      <display-name>StrutsApplication1</display-name>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <description></description>
        <display-name>LoginServlet</display-name>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>login.LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
    </web-app>
    *************************