Tuesday, February 10, 2015

How to Show Alert Dialog in Android

Android Alert Dialog is one of the most important and basic component in Android applications.  This dialog is used to show alerts to the users, get confirmation from the users.
There are three parts in the alert dialog.
      -Title
      -Content
     - Action Button(s)
In these three parts, ‘Title’ is an optional part.
Content:
This part is used to show the message to the user. In the sample alert dialog shown above ‘Sample One Action Button Alert’ is the content.
This content can be a string message or a list or any custom layout.
Action Button:
This is one of the important parts in the alert dialog. This is used to interact with the user. In the sample alert dialog shown above ‘OK’ is the action button.
Action buttons can be any one of the below three types;
Positive action button
Negative action button
Neutral action button

You can add all three types of action buttons to the Android alert dialog. It depends on the need. But you cannot add more than three action buttons in an alert dialog. Which means a particular type of action button cannot be added more than once.
So an alert dialog can have maximum of one positive, one negative and one neutral action button.
Normally positive action button is used to accept the action. (OK/YES)
Negative action is used to cancel the action. (NO)
Neutral action is used in neutral situations (May be later)

Creating alert dialog is very easy. In this tutorial i will be discussing about creating different alert dialogues with one button(ok button), two buttons(yes or no buttons) and three buttons(yes, no and cancel buttons).

Android alert dialog with One button

The following code will create a simple alert dialog with one button. In the following code setTitle() method is used for set Title to alert dialog. setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog.

Write below code where you want alert dialog box in your project.

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
        // Setting Dialog Title
        alertDialog.setTitle("Succesfully send!");
        // Setting Dialog Message
        alertDialog.setMessage("Check your email and verify your username and password...");
        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.icon);
        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                // Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT)
.show();
                }
        });
        // Showing Alert Message
        alertDialog.show();



Android alert dialog with two button

The following code will create alert dialog with two button. setPositiveButton() is used to create a positive button in alert dialog and setNegativeButton() is used to invoke negative button to alert dialog.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
        // Setting Dialog Title
        alertDialog.setTitle("Set Title here");
        // Setting Dialog Message
        alertDialog.setMessage("Set the Text Message here");
        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.delete);
        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            // Write your code here to invoke YES event
            Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
            }
        });
        // Setting Negative "Cancel" Button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // Write your code here to invoke NO event
            Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
            dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();



Android alert dialog with three button

Here setNeutralButton() is used to create a neutral cancel button

AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
                // Setting Dialog Title
                alertDialog.setTitle("Save File...");
                // Setting Dialog Message
                alertDialog.setMessage("Do you want to save this file?");
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.save);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    // User pressed YES button. Write Logic Here
                    Toast.makeText(getApplicationContext(), "You clicked on YES",
                                        Toast.LENGTH_SHORT).show();
                    }
                });
                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    // User pressed No button. Write Logic Here
                    Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                    }
                });
                // Setting Netural "Cancel" Button
                alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(), "You clicked on Cancel",
                                        Toast.LENGTH_SHORT).show();
                    }
                });
                // Showing Alert Message
                alertDialog.show();

Friday, February 6, 2015

How to implement Splash Screen in Android

Android splash screen are normally used to show user some kind of progress before the app loads completely. Some people uses splash screen just to show case their app / company logo for a couple of second. In this tutorial we are going to learn how to implement splash screen in our android application.

Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. Main activity name as MainActivity.java
For Splash Screen we are creating a separate activity. Create a new class in your package and name it as SplashScreen.java
In AndroidManifest.xml file make your splash screen activity as Launcher activity.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.splashscreentimer"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="21" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- Splash screen -->
        <activity
            android:name="com.example.splashscreentimer.SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" /
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Main activity -->
        <activity
            android:name="com.example.splashscreentimer.MainActivity"
            android:label="@string/app_name" >
 </activity>
 </application>
</manifest>
The code for activity_splash.xml in which we give the image name in android:backgroud attribute and save that image in drawable folder.Here we use the image file name background_image.
activity_splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background_image" >
</RelativeLayout>
Now the code for splashscreen.java
package com.example.splashscreentimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class SplashScreen extends Activity {
    // Splash screen timer
    private static int SPLASH_TIME_OUT = 3000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        new Handler().postDelayed(new Runnable() {
            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */
            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);
                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}


Thursday, February 5, 2015

How to switch between Activities in Android

In Android user interface is displayed through an activity. In Android app development you have to face situations where you need to switch between one Activity (Screen) to another. In this tutorial we will be discussing about switching between one Activity to another and sending data between the activities.Here we explain with the help of stable android IDE Android Studio.

For this purpose we use a class Intent. And uses the methods of intent class for sending data between activities.
To open new activity we use startActivity() method
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
StartActivity(i);

To send parameter to newly created activity putExtra() method will be used.
i.putExtra("key", "value");
example
i.putExtra("Name","xyz");

To receive parameters on newly created activity getStringExtra()  method will be used.
Intent i = getIntent();
i.getStringExtra("key");
String name = i.getStringExtra("Name");

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(First.xml, Second.xml) and two Acvities (First.java,Second.java). In which we are switching between them.

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



The code for First.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class First extends Activity implements OnClickListener {
     Button b1;
     EditText e1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        b1=(Button)findViewById(R.id.button1);
e1=(EditText)findViewById(R.id.editText1);
        b1.setOnClickListener(this);
}
      @Override
     public void onClick(View arg0) {
           // TODO Auto-generated method stub
           Intent in=new Intent(this,Second.class);
           in.putExtra("ack",e1.getText().toString());
           startActivity(in);}}

The code for Second.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Second extends Activity implements OnClickListener {
     Button b2;
     EditText e2;
    @Override
    protected void onCreate(BundlesavedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.two);
        b2=(Button)findViewById(R.id.button2);
e2=(EditText)findViewById(R.id.editText2);
        b2.setOnClickListener(this);
        Intent i=getIntent();
String s=i.getStringExtra("ack");
        e2.setText(s);
 }
     @Override
     public void onClick(View arg0) {
           // TODO Auto-generated method stub
     finish();
     }
}

The code for first.xml
<LinearLayout 
xmlns:android="http://schemas.android.com/app/res/android"  
        xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/container"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:gravity="fill_vertical"
     android:orientation="vertical" >
 <EditText android:id="@+id/editText1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:ems="10">
  <requestFocus /> 
  </EditText>
  <Button android:id="@+id/button1"
          android:layout_width="118dp"
          android:layout_height="102dp" 
          android:text="Button" /> 
  </LinearLayout>
The code for second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/container"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:gravity="fill_vertical"
     android:orientation="vertical" >
 <EditText android:id="@+id/editText2"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:ems="10">
  <requestFocus />
  </EditText>
  <Button android:id="@+id/button2"
          android:layout_width="118dp"
          android:layout_height="102dp" 
          android:text="Button" />
  </LinearLayout>

The mainfiest.xml
<?xml version="1.0" encoding="utf-8" 
?> 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intent"
    android:versionCode="1"
    android:versionName="1.0">
  <uses-sdk 
       android:minSdkVersion="15"
       android:targetSdkVersion="21" /> 
 <application android:allowBackup="true"
               android:icon="@drawable/ic_launcher" 
               android:label="@string/app_name"
               android:theme="@style/AppTheme">
 <activity android:name="com.example.intent.first"
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="com.example.intent.Second"
l̥android:label="@string/app_name">
 <intent-filter
  <category android:name="android.intent.category.DEFAULT" /> 
  </intent-filter>
  </activity>
  </application>

  </manifest>

Sunday, January 11, 2015

Ice Breaking Android Program

In this tutorial, we will go through the necessary steps you need to take in order to develop your first Android application in Eclipse IDE using the ADT plugin and run it with an Android Virtual Device. We can also use android official IDE Android studio.
The ADT plugin provides easy Android Project creation and management with rich editor features and documentation as well as Android Virtual Device (AVD) management. The workflow on Eclipse and Android studio is similar its depends on you which one you select. we will explain here using Eclipse IDE.
The steps :
  1. Download and Install the Android SDK
  2. Download and Install the ADT Eclipse plugin
  3. Create an Android Virtual Device (AVD)
  4. Create an Android Project with Eclipse
  5. Run the Application in the Android Virtual Device

Create Android Application

The first step is to create a simple Android Application using Eclipse IDE. Follow the option File -> New -> Project and finally select Android New Application wizard from the wizard list. Now name your application as HelloWorld using the wizard window as follows:
Hello Android Wizard
Next, follow the instructions provided and keep all other entries as default till the final step. Once your project is created successfully, you will have following project screen:
Hello Android Project

Anatomy of Android Application

Before you run your app, you should be aware of a few directories and files in the Android project:
Android Directory Structure
S.N.Folder, File & Description
1src
This contains the .java source files for your project. By default, it includes an MainActivity.javasource file having an activity class that runs when your app is launched using the app icon.
2gen
This contains the .R file, a compiler-generated file that references all the resources found in your project. You should not modify this file.
3bin
This folder contains the Android package files .apk built by the ADT during the build process and everything else needed to run an Android application.
4res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density screens.
5res/layout
This is a directory for files that define your app's user interface.
6res/values
This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions.
7AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines each of its components.

The Main Activity File

The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World! application:
package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. TheonCreate() method is one of many methods that are fi red when an activity is loaded.

The Manifest File

Whatever component you develop as a part of your application, you must declare all its components in a manifest file called AndroidManifest.xml which ressides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.helloworld"
   android:versionCode="1"
   android:versionName="1.0" >
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="15" />
   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       <activity
           android:name=".MainActivity"
           android:label="@string/title_activity_main" >
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER"/>
           </intent-filter>
       </activity>
   </application>
</manifest>