Thursday, 24 May 2012

              MD5 Encryption in Android

Lets start the tutorial for md5 encryption in android.

MD5 is the best practice to handle the secured data like password etc.
In android we can able to achieve this using few simple code.

Create new android project and copy and paste the below java code.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DataEncryptionActivity extends Activity {
    String strNormalValue, strEncrytedValue;
    EditText edtValue;
    Button btnEncrypt;
    TextView tvEncrypt;

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

        edtValue = (EditText) this.findViewById(R.id.edt_to_encrypt);
        tvEncrypt = (TextView) this.findViewById(R.id.txt_encrypt);
        btnEncrypt = (Button) this.findViewById(R.id.btn_encrypt);
        btnEncrypt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                strNormalValue = edtValue.getText().toString().trim();
                strEncrytedValue = getMD5(strNormalValue);
                tvEncrypt.setText(strEncrytedValue);
            }
        });

    }

    public String getMD5(String src) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("MD5");
            digest.update(src.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String h = Integer.toHexString(0xFF & messageDigest[i]);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}


Copy and paste it in main.xml

<?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" >

    <EditText
        android:id="@+id/edt_to_encrypt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_encrypt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Convert to MD5" />

    <TextView
        android:id="@+id/txt_encrypt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:singleLine="false" />

</LinearLayout>




 Full Source code for MD5 Encryption.

Friday, 11 May 2012

                Android Login Email & Password Validation

Here i going to validate the email and password.
The complete source code for the LoginValidationProject

follow my steps, Create the project with following attributes.

Project name         : LoginValidationExample
Build Target           : Android 2.1
Application name   : LoginValidationExample
Package name        : com.android.dhamu.validation
Create Activity      : LoginScreen

Step 1:

 Rename the main.xml file as login_screen.xml. Copy and paste the below xml coding in it.

<?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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Login Screen"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#00ff00" />

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:orientation="vertical" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:layout_margin="30dip"
            android:orientation="vertical" >

            <EditText
                android:id="@+id/edt_username"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dip"
                android:layout_marginTop="20dip"
                android:hint="Username"
                android:inputType="textEmailAddress"
                android:paddingLeft="10dip"
                android:paddingRight="10dip"
                android:singleLine="true"
                android:typeface="normal" >

                <requestFocus>
                </requestFocus>
            </EditText>

            <EditText
                android:id="@+id/edt_password"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dip"
                android:layout_marginTop="10dip"
                android:hint="Password"
                android:inputType="textPassword"
                android:paddingLeft="10dip"
                android:paddingRight="10dip"
                android:password="true"
                android:singleLine="true"
                android:typeface="normal" >
            </EditText>

            <Button
                android:id="@+id/btn_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Login" >
            </Button>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


Now you got the screen like



Step 2:

Create the home_screen.xml in res/layout folder, Then copy and paste the below xml coding in it.

<?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:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Home Screen"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#00ff00" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login completed successfully"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ff00ff" />
    </LinearLayout>

</LinearLayout>

Now you got the screen like


Step 3:

Copy the below java coding and paste it in LoginScreen.java file.

package com.android.dhamu.validation;

import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginScreen extends Activity {
    EditText edtUsername,edtPassword;
    Button btnLogin;
    String strUsername,strPassword;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_screen);
       
        edtUsername = (EditText)this.findViewById(R.id.edt_username);
        edtPassword = (EditText)this.findViewById(R.id.edt_password);
        btnLogin = (Button)this.findViewById(R.id.btn_login);
       
        btnLogin.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                strUsername = edtUsername.getText().toString().trim();
                strPassword = edtPassword.getText().toString().trim();
               
               
                if (isInternetConnected()) {

                    if (isUserNameNotEmpty()) {

                        if (isValidEmail()) {

                            if (isPassWordNotEmpty()) {
                               
                                LoginScreen.this.startActivity(new Intent(
                                        LoginScreen.this,
                                        HomeScreen.class));
                            }
                        }

                    }

                }
               
               
            }
        });
       
    }
   
   
    public boolean isInternetConnected() {

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState() == NetworkInfo.State.CONNECTED
                || connectivityManager.getNetworkInfo(
                        ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            return true;
        } else
            Toast.makeText(this, "Please check your internet connection",
                    Toast.LENGTH_SHORT).show();
        return false;
    }

   
    // Checking the Email whether it is valid or not.

    private boolean isValidEmail() {
        final Pattern EMAIL_ADDRESS_PATTERN = Pattern
                .compile("[a-zA-Z0-9+._%-+]{1,256}" + "@"
                        + "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" + "(" + "."
                        + "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" + ")+");

       

        if (EMAIL_ADDRESS_PATTERN.matcher(strUsername).matches()
                && !strUsername.equalsIgnoreCase("")) {

            return true;
        } else {
            Toast.makeText(this, "Please enter valid Email ID", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }

    }
   

    // Checking whether the username is not empty

    public boolean isUserNameNotEmpty() {
        if (strUsername.equalsIgnoreCase("")) {
            Toast.makeText(this, "Please enter the Email ID", Toast.LENGTH_SHORT)
                    .show();
            return false;
        } else {
            return true;
        }

    }

   
    // Checking whether the password is not empty

    public boolean isPassWordNotEmpty() {
        if (strPassword.equalsIgnoreCase("")) {
            Toast.makeText(this, "Please enter the Password", Toast.LENGTH_SHORT)
                    .show();
            return false;
        } else {
            return true;
        }

    }

}

Step 4:

Create the HomeScreen.java in src folder and paste the below java code in it.

package com.android.dhamu.validation;

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

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

Step 5:

AndroidManifest.xml file

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

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

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

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

</manifest>
In AndroidManifest.xml file,

1) Add the permission for INTERNET and ACCESS_NETWORK_STATE.
2) Add the HomeScreen.java in application.

Here is the complete SourceCode for LoginValidation.



Tuesday, 8 May 2012

  Android TitleBar And  CustomTitleBar


This is possible to handle the titlebar and also can able to customize it in android.
We can do this via
A) Adding xml code in AndroidManifest.xml
B) Using java code by programmatically.


                                   Working in AndroidManifest.xml


Hide the Title Bar Using XML code.



If you want to hide the title bar for particular activity, use the below code in AndroidManifest.xml within the <activity> tag.


 android:theme="@android:style/Theme.Black.NoTitleBar"

Example:
     <activity
            android:name=" FirstScreen"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Black.NoTitleBar " >

 Hide the Title Bar and Status Bar Using XML code.

If you want to hide the Title Bar and Status Bar for particular activity, use the below code in AndroidManifest.xml within the <activity> tag.

android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"

Example:
     <activity
            android:name=" FirstScreen"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen " >

Hide the Title Bar and Status Bar for entire Application Using XML code.

 If you want to hide the Title Bar and Status Bar for entire application,just use the above code in <application> tag.

Example:

 for hiding title bar:
        <application
        android:icon="@drawable/icon"
         android:label="@string/app_name"
         android:theme="@style/CustomTheme"
         android:theme="@android:style/Theme.Black.NoTitleBar" >

 for hiding title and status bar:
        <application
        android:icon="@drawable/icon"
         android:label="@string/app_name"
         android:theme="@style/CustomTheme"
         android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >

                Working in Java file using java code

Hide the Title Bar Using java code.

If you want to hide the title bar for particular activity, use this java code above the setContentView() method.

requestWindowFeature(Window.FEATURE_NO_TITLE);
   
                                    Custom Title Bar in Android

* Follow the steps carefully to make custom title bar
* Copy and paste the below coding in corresponding files.
* Create the new Android Project with following attributes.

Project name        : CustomTitleBars
Build Target          : Android 2.1
Application name  : CustomTitleBars
Package name      : com.custom.title.bars
Create Activity     : FirstScreen

Step 1:

Create the custom_title.xml file in res/values folder.

<resources>
       <style name="CustomTitleBars">
              <item name="android:background">#00ffff</item>
    </style>
   
    <style name="CustomTitle" parent="android:Theme">
       <item name="android:windowTitleSize">35dip</item>
        <item name="android:windowTitleBackgroundStyle">@style/CustomTitleBars</item>
    </style>
</resources>

Step 2:

Create the first_title_screen.xml file in res/values folder.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="horizontal"
       android:layout_width="fill_parent"
       android:layout_height="35dip"
       android:background="#00ffff" android:gravity="right">

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="35dip"
        android:text="NEXT"/>
          
</LinearLayout>

Step 3:

Create the second_title_screen.xml file in res/values folder.

<?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="35dip"
    android:background="#00ffff"
    android:orientation="horizontal">

    <Button
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="35dip"
        android:text="BACK" />

</LinearLayout>

Step 4:

Paste the below coding in main.xml

<?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:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_screen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#00ff00"
        android:textSize="25dip"
        android:textStyle="bold"
        android:typeface="serif" />

</LinearLayout>

Step 5:

 Paste this code in FirstScreen.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class FirstScreen extends Activity {

       Button btnNext;
       TextView tvScreen;
       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);

              requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
             
              setContentView(R.layout.main);
              getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                           R.layout.first_title_screen);
      
              tvScreen = (TextView)this.findViewById(R.id.tv_screen);
              tvScreen.setText("First Screen");
              btnNext = (Button) this.findViewById(R.id.btn_next);
              btnNext.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           Intent intent =new Intent(FirstScreen.this,SecondScreen.class);
                           startActivity(intent);
                          
                     }
              });
       }
}

Step  6:

Create the SecondScreen.java file in src folder.

package com.custom.title.bars;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class SecondScreen extends Activity {

       Button btnBack;
       TextView tvScreen;
       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);

              requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
             
              setContentView(R.layout.main);
              getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                           R.layout.second_title_screen);
      
              tvScreen = (TextView)this.findViewById(R.id.tv_screen);
              tvScreen.setText("Second Screen");
              btnBack = (Button) this.findViewById(R.id.btn_back);
              btnBack.setOnClickListener(new OnClickListener() {

                     @Override
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           finish();
                          
                     }
              });
       }
}

In Android Manifest file 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.custom.title.bars"
    android:versionCode="1"
    android:versionName="1.0" >
    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/CustomTitle" >
        <activity
            android:name="FirstScreen"
            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="SecondScreen" >
        </activity>
    </application>
</manifest>

Full source code for Custom Title Bars