BFS & DFS

A traversal is a systematic walk which visits the nodes of the graph in a specific order.
Two Types:-
1.Breadth First Traversal
2.Depth First Traversal

Breadth First Traversal-

It traverses the successors of the start node,generation after generation in a horizontal or linear fashion.

Algorithm-

BFT(s)
{
//s is the start vertex of the traversal in an undirected graph G.
//Q is a queue which keeps track of the vertices whose adjacent nodes are to be visited.
//Vertices which have been visited have their ‘visited’ flags set to 1.
//Initially,visited(vertex) = 0 for all vertices of graph G.
//queue is a linear list in which all insertions are made at one end and all deletions are made at the other end.

Initialize queue Q;

visited(s)=1;

ENQUEUE (Q,s) //insert s into queue Q

while (Q is not empty) //process until Q is empty
{
DEQUEUE(Q,s) //delete s from Q

print (s); //output the vertex visited.

for all vertices v adjacent to s
{
if(visited[v]=0)
{
ENQUEUE(Q,v);
visited(v)=1;
}
}
}
}

Code-

[cpp]
vector<int>a[1005];
int visited[1000]={0};
//N is the number of nodes and M is the number of edges
//preparing adjacency list
for(i=0;i<M;i++)
{
scanf(“%d %d”,&x,&y);
a[x].push_back(y);
}
queue<int> q;
visited[s]=1;
q.push(s);
while(!q.empty())
{
s=q.front();
//retrieving the element which is to be deleted.
printf(“%d “,s);
q.pop();
//checking vertices adjacent to s
for(int i=0;i<a[s].size();i++)
{
if(visited[a[s][i]]==0)
{
visited[a[s][i]]=1;
q.push(a[s][i]);
}
}
}
[/cpp]

Depth First Traversal-

This traversal visits each node,that is,the first occurring among its adjacent nodes and successively repeats the operation,thus moving deeper and deeper into the graph.In contrast,BFT moves side ways or breadth ways in the graph.

Algorithm-

DFT(s)
{
// s is the start vertex
visited(s)=1;
print (s);
for each vertex v adjacent to s
{
if( visited(v)=0 ) {DFT(v);}
}
}

Code-

[cpp]
vector<int>a[1005];
int visited[1000]={0};
//N is the number of nodes and M is the number of edges
//preparing adjacency list
for(i=0;i<M;i++)
{
scanf(“%d %d”,&x,&y);
a[x].push_back(y);
}
for(int i=0;i<N;i++)
{
if(visited[i]==0)
{
dfs(i);
}
}
void dfs(int node)
{
visited[node]=1;

printf(“%d “,node);

for(int i=0;i<a[s].size();i++)
{
if(visited[a[s][i]]==0)
{
dfs(a[s][i]);
}
}
}

[/cpp]

NOTE-

If an adjacency matrix is used to represent the graph,the time complexity in both the traversals will be O(N^2). But,the use of adjacency list results in a time complexity of O(N).

All about Factorial(!)

In mathematics,the factorial of any positive number N is the product of the positive integers less than or equal to N.It is denoted by ‘N!’.

Example-

5!= 5*4*3*2*1 =120
Also,0!=1.

In C/C++,no data type can store the value of factorial of a number greater than 20.To find the factorial of greater numbers easily,JAVA/Python can be used.

JAVA Code-

This code uses BigIntegers.

[cpp]
import java.io.*;
import java.math.BigInteger;
public class Main
{
public static void main(String[] args) throws IOException
{
String n;
BufferedReader d= new BufferedReader(new InputStreamReader(System.in));
n=d.readLine();
int y=Integer.parseInt(n);
BigInteger x=new BigInteger(n); //converting string to biginteger
for(int j=y-1;j>=1;j–)
{
String str= Integer.toString(j);
x=x.multiply(new BigInteger(str));
}
System.out.println(x);
}
}
[/cpp]

Length of the factorial-

The number of digits in N! is approximately:-
[(log(2*pie*n)/2)+n*(log(n)-1))/log(10)]+1;

Stirling’s approximation-

N! is approximately equal to {sqrt(2*pie*n)}*{(n/e)^n}.

To find the power of a prime factor of N! –

Let the prime factor be X.Then,the power of X will be :-

[N/X]+[N/(X^2)]+[N/(X^3)]+….. where [.] denotes the greatest integer function.

For example-

Power of 2 in 5! will be-

[5/2]+[5/4]+[5/8]+[5/16]+…..
=> 2+1+0+0+….
which is equal to 3.

Also,5!=2^3 * 3^1 * 5^1

To find the number of zeroes at the end of N!-

Find the power of 2 and 5 in N!(Since,10=5*2).
Let it be ‘v’ and ‘s’ respectively.
if(v<=s),then number of zeroes at the end is ‘v’,else,’s’.

Code-

[cpp]
//initialization
s=0;
v=0;

p=N; //copying value of N to another variable
//Finding power of 5
while(N>0)
{
q=N/5;
s=s+q;
N=q;
}
//Finding power of 2
while(p>0)
{
w=p/2;
v=v+w;
p=w;
}

if(v>=s) printf(“%d\n”,s);
else printf(“%d\n”,v);
}
[/cpp]

Last Non-zero digit of the factorial-

Lets say D(N) denotes the last non zero digit of factorial, then the algo says:-
If tens digit of N is odd,D(N)=4*D[N/5]*D(Unit digit of N)
If tens digit of N is even,D(N)=6*D[N/5]*D(Unit digit of N)
where [N/5] is greatest Integer Function.

Example-

D(26)=6*D[26/5]*D(6)=6*D(5)*D(6)=6*2*2=4
[D(5) means last non zero digit of 5!=120 which is 2, same for D(6)]

Android development primer: Creating layouts for Alert Dialog

Don’t like the traditional way in which the Alert Dialog appears? Would you rather have a custom layout for it? Well, not a problem at all. In this post I will show you exactly how to do that. I would like you to know that there are other types of Dialogs that you can have. You can have custom layouts for each of them too. You could customize dialogs to contain EditTexts and take inputs from the user.
Complete Source Code is at the bottom.

So open up an activity and start coding.

  • First of all we will create a layout for our Dialog. So navigate to <yourprojectname> -> res -> layout. Create a new XML file and choose the type of layout you want.
  • Here I will insert two EditTexts in the Alert Dialog. You can follow along or create your own custom layout.Write in the following code into your XML file.
    <?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" >
    
        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:ems="10" >
    
            <requestFocus />
        </EditText>
    
        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/editText1"
            android:ems="10" />
    
    </RelativeLayout>
  • Now that we have the layout ready, we will need to refer to it from our java code. Go to the concerned activity and make sure you have a way to trigger the dialog, for e.g. a Button. I have a button and I will trigger the Alert Dialog at the click of the button.
  • Write the following code in the onClick() function inside the onClickListener() constructor.
    [java]
    LayoutInflater lf = LayoutInflater.from(Main.this);
    final View DialogView = lf.inflate(R.layout.dialog, null);
    AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
    alert.setTitle(“Test Alert Dialog”).setView(DialogView).setMessage(msg).setPositiveButton(“Yes”,
    new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), “Yes”, Toast.LENGTH_LONG).show();
    }
    }).setNegativeButton(“No”,
    new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), “No”, Toast.LENGTH_LONG).show();
    }
    });
    alert.show();

    [/java]

  • For now it will be enough for you to know that LayoutInflater is used to inflate or in simple terms set the layout of a View. I will discuss it in a later post.
  • If you have read my previous post, you will notice that there is only a slight change in the code for the AlertDialog. We are now also using a function setView() here. It’s name reflects exactly what it is used for. This is the way we can force an AlertDialog to possess a design/layout of our choice.
  • Save everything and execute it on an emulator/device.

layoutalert

Here’s how it looks like on my Eclair emulator. You can choose to have different background color for the dialog, add more fields etc.

COMPLETE SOURCE CODE

dialog.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" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:ems="10" />

</RelativeLayout>

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <Button
        android:id="@+id/but"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Button" />

</RelativeLayout>

MainActivity.java

[java]
package com.nero.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.but);
final String msg=”This is a test Alert Dialog Box”;

but.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
LayoutInflater lf = LayoutInflater.from(MainActivity.this);
final View DialogView = lf.inflate(R.layout.dialog, null);
AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
alert.setTitle(“Test Alert Dialog”).setView(DialogView).setMessage(msg).setPositiveButton(“Yes”,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), “Yes”, Toast.LENGTH_LONG).show();
}
}).setNegativeButton(“No”,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), “No”, Toast.LENGTH_LONG).show();
}
});
alert.show();
}
});

}
}

[/java]

Android development primer: Creating Alert Dialogs in Android

In Android devices, probably the thing that we come across most frequently is Alert Dialog Boxes. If you are not familiar with an Alert Dialog Box, here’s what it looks like on an Eclair emulator.

alert1

You should know that the Dialog’s title, text and the buttons are customizable and can be made to read anything.
We’ll see how to do it in a minute. So open an activity and start coding. Complete Source Code is at the bottom.

  • For the layout of the activity insert a button. We will make the Alert Dialog appear when the button is pressed.
  • Set the content view of the Activity and add declare the button from the layout in the java file.
  • We will now set the onClickListener() attribute of the button. Write the following code in the onClick() function of the onClickListener() attribute.
    [java]
    AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
    alert.setTitle(“Test Alert Dialog”).setMessage(msg).setPositiveButton(“Yes”,
    new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), “Yes”, Toast.LENGTH_LONG).show();
    }
    }).setNegativeButton(“No”,
    new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), “No”, Toast.LENGTH_LONG).show();
    }
    });
    alert.show();
    [/java]

  • If it is not clear have a look at the complete Source Code at the bottom to understand what you need to do.
  • If you take some time and go through the AlertDialog code snippet, you can see that the components used in it are quite mnemonic. The functions such as setTitle()setMessage()setPositiveButton()setNegativeButton() represent exactly what they do. However in case you have an issue understanding them, drop a comment and I will explain it the best I can.
  • Save the activity and execute in an emulator/device.
  • Below images shows the results of clicking the Yes and No button on the Alert Dialog respectively.

alert2   alert3

COMPLETE SOURCE CODE

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <Button
        android:id="@+id/but"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Button" />

</RelativeLayout>

Main.java

[java]
package com.nero.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.but);
final String msg=”This is a test Alert Dialog Box”;
but.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
alert.setTitle(“Test Alert Dialog”).setMessage(msg).setPositiveButton(“Yes”,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), “Yes”, Toast.LENGTH_LONG).show();
}
}).setNegativeButton(“No”,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), “No”, Toast.LENGTH_LONG).show();
}
});
alert.show();
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

[/java]

Here, we are making a simple Toast appear on the Click of the Positive or the Negative button of the Alert Dialog. Once you are into making complex applications, you will be doing much more than this with the Alert Dialog.

Binomial Coefficient

Binomial Coefficient is represented by nCk which means number of ways of choosing k objects from n objects.It is the coefficient of x^k term in the polynomial expansion of (1+x)^n.It also represents an entry in Pascals Triangle.

Properties-

1. nCk=(n!)/[(k!)*(n-k)!]
2. nCn=1
3. nC0=1
4. nCk=(n-1)C(k)+(n-1)C(k-1)
5. nCk=(n)C(n-k)

The task is to find the value of nCk given the values of n and k.

Recursive solution-

[cpp]
int binomialCoeff(int n, int k)
{
// Base Cases
if (k==0 || k==n)
return 1;

// Recurrence
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
}
[/cpp]

For large values of n,there will be many common subproblems.For example-
To calculate 5C2,function will be called for 4C2 and 4C1.
To calculate 4C1,function will be again called for 3C0 and 3C1.
To calculate 4C2,function will be called for 3C1 and 3C2.
So,3C1 is being calculated twice.
This problem has overlapping sub-problems property.Re-computation of same sub-problems can be avoided by constructing a temporary array C[][] and storing the results like we do in other dynamic programming problems.

DP based solution-

[cpp]
//C[][] is the temp array

for(i=0;i<=n;i++)
{

for(j=0;j<=i;j++)
{

//base condition
if((i==0)||(j==0)) C[i][j]=1;

else C[i][j]=C[i-1][j-1]+C[i-1][j];
}
}
//C[n][k] gives the result
[/cpp]

Time Complexity of this code is O(n*k).

Note-

n,k are non negative integers.
nCk is valid only for n>0 and 0<=k<=n.

Android development primer: Know the AndroidManifest.xml

Enough programming. Let’s take a break and look into one of the vital components of any Android application, the AndroidManifest.xml file. Every Android application must have an AndroidManifest.xml file with that exact name, in its root directory. It provides the Android system important information about the application you are about to run in the device.

Navigate to <yourprojectname> -> AndroidManifest.xml. I will give you a brief overview of what purpose do the various sections of the manifest serve. Some of these might not be present in your manifest file. That is because components are added in the manifest file according to the needs of the developer. Nonetheless it will do you good to know about them.

  • package : This names the package your Android Application is in. You can change this at any time you want, but it will require further changes in each java file in your application.
  • versionCode : This is the version code of your application. This is useful when you are modifying you application and want to have a clean copy of the application as another version.
  • versionName : You can also name the version of your application. Change this to your liking.
  • minSdkVersion : While creating the project you must have selected a minimum API level. Devices having android versions below this API will not be able to run your application.
  • targetSdkVersion : While creating the project you must have selected a target API level. Devices having android versions below this API (and above the minimum API level) will be able to run your application, but you have indicated that this API is the one you are particularly targeting.
  • icon : This is the icon that will appear once the application has installed in your device. You can have an image in the drawable folder and make that you application icon.
  • label : This is the name of your application. Your application will be installed in the device or uploaded to the Android market by this name. The default value is @string/app_name. I will talk about what that is and how to change it in a later post.
  • theme : This is the basic theme of your application. It is the one you selected while first creating a project.
  • activity -> name : This is the name of you activity. There will be as many activity tags in your manifest, as there are activities in your application. Each activity must be declared in the manifest, failing which your application will crash as soon as you try to navigate to an undeclared activity.
  • activity -> screenOrientation : This indicates the orientation of the screen that the developer wants his application to have. It can have two possible values – portrait and landscape. For simplicity, portrait is vertical and landscape is horizontal. These are used when you do not want to auto-rotate the screen when the device is rotated. If the screenOrientation attribute is not specified, it indicates auto-rotation of the device screen is allowed.
  • intent-filter : If you have read my previous posts, I told you that an intent is used to push the current activity into the back stack and call upon another activity. The intent filter here acts in the same way. This, by default is present in only one activity MainActivity. That is because it is the activity which is first displayed when the application is launched. Since we are not switching from one activity to another here thus the Android system’s intent is used to do this.
  • receiver : Just like there are activities in the application, it can also contain broadcast receivers.  Each broadcast receiver must be declared in the manifest.
  • uses-permission : This is an interesting component. Your application might use some data or features from the user’s device that might/might not be acceptable to the user. In order to let the user know that some specific features and data are required in order for your application to work, uses-permission is used. This informs the user, at the time of installation of the application about these requirements. It is only after the user approves, that your application will be installed.
  • It also declares the permissions other applications need in order to communicate with your application.
  • The manifest also lists the library against which the application must be linked, if any.

So, you can see that the AndroidManifest.xml file serves the most important purpose of letting the Android system and the user know about what your application needs, what it does and other vital details.
Above are the most frequently seen/used components of the android manifest file. You might come across many more as you step into advanced Android Programming.

Longest Increasing Sub-sequence

Given a sequence of numbers,we need to find the longest increasing sub-sequence from the given input(not necessary continuous).

Example-

Input- 1 10 4 5 3 2 9 11 13

Increasing Sub-sequences-

1 4 5
5 9 11 13
10 11 13
4 5 9,etc

Longest Increasing Sub-sequence– 1 4 5 9 11 13
Length of Longest Increasing Sub-sequence(LIS) – 6

Naive Algorithm-

Check all the sub-sequences,but its time complexity will be approximately O(n^2) where n is the number of elements.

Efficient Algorithm-

x[] is the input sequence.Let it be 1 10 4 5 3 2 9 11 13.
The first element to be added in m[] is the first element of the input sequence.
Each element of the input sequence is taken one by one.
1. If it is greater than or equal to the last element of m[],insert the element in m[] at the end.
2. Else,replace the element in m[] which is just greater than element of the input sequence with the selected element of the input sequence.

Finally,the length of the array m[] is the length of the longest increasing sub-sequence.
Note-Elements of m[] are not elements of LIS.The actual values in the sub-sequence can be found by storing them in another array during the loop.

Illustration-

m=[]
m=[1]
m=[1 10]
m=[1 4] // 10 is replaced by 4 as number just greater than 4 is 10.
m=[1 4 5]
m=[1 3 5] //4 is replaced by 3 as number just greater than 3 is 4.
m=[1 2 5] //3 is replaced by 2 as number just greater than 2 is 3.
m=[1 2 5 9]
m=[1 2 5 9 11]
m=[1 2 5 9 11 13]

Thus,length of LIS is 6,that is size of m[].

Code-

[cpp]
m[1]=a[0];
p=2;
for(i=1;i<n;i++)
{
s=1;
//finding element just greater than x[i]
for(j=1;j<p;j++)
{
if(x[i]<m[j])
{
m[j]=x[i];s=0;break;
}
}
//value of s determines if element just greater than
// x[i] is found or not.
//If not found,then it is inserted at the end.
if(s==1){m[p]=x[i];p++;}
//p-1 is the size of the array and
// thus the length of LIS.
}
[/cpp]

N Queens Problem (Backtracking)

Given a chess board of size n*n,the task is to find all the ways to place n queens so that they don’t attack each other.
In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally.

Naive Algorithm-

[cpp]
while there are untried configurations
{
generate the next configuration
if queens don’t attack in this configuration then
{
print this configuration;
}
}
[/cpp]

Backtracking Algorithm-

If queens are at (i,j) and (k,l) coordinates,then they can attack each other if:
1. i=k (same row)
2. j=l (same column)
3. |i-k|=|j-l| (diagonally),| | denotes the absolute value

[cpp]
bool place(k,i)
{
//returns true if the queen can be placed at k-th row and i-th column
//x[] is a global array with first (k-1) values set already.
//x[p]=q means a queen is at location (p,q)

for(j=1 to k-1)
{
if(x[j]==i)||(ABS(x[j]-i)==ABS(j-k)) //checking if another queen in same column or diagonally
return false;
}
return true;
}
[/cpp]

To print all possible placements using backtracking:

[cpp]
void NQueens(k,n)
{

for(i=1 to n)
{
if(place(k,i)) //checking if queen can be placed at (k,i)
{
x[k]=i;
if(k==n) then write (x[1:n]);
else Nqueens(k+1,n);
}
}
}
[/cpp]

Android development primer: Creating Options Menu in Android – Part IV

This is the last post in the  Creating Options Menu in Android section. I told you in the first post of this section, that the Options Menu layout can also be created using  XML. In this post I am going to show you how.

I will be editing my codes from previous posts. You can create a new project and follow along. I would recommend creating a new project because we will not be changing the default code provided in the MainActivity.java much. Complete Source Code is at the bottom.

  • Navigate to <yourprojectname> -> res -> menu -> main.xml. Open the main.xml file.
  • You can already see one item in it. That is provided by default. You may or may not delete it.
  • Write the following code before the closing menu tag i.e. before </menu>.
    <item
            android:id="@+id/menuitem1"
            android:title="MenuItem1"
            android:icon="@drawable/menuitemicon1" />
    
    <item
            android:id="@+id/menuitem2"
            android:title="MenuItem2"
            android:icon="@drawable/menuitemicon2" />
  • Switch over to MainActivity.java and in the onCreateOptionsMenu() method, write the following
    [java]
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    [/java]
  • Save and execute the application on the emulator/device.
  • In order to use the onOptionsItemSelected() method, write the following code in the method
    [java]
    switch (item.getItemId()) {
    case R.id.menuitem1:
    Toast.makeText(getApplicationContext(), “MenuItem1 selected”, Toast.LENGTH_LONG).show();
    return true;
    case R.id.menuitem2:
    Toast.makeText(getApplicationContext(), “MenuItem2 selected”, Toast.LENGTH_LONG).show();
    return true;
    }
    return super.onContextItemSelected(item);
    [/java]
  • Remember that unlike the previous post, the cases here will not be 1,2.. but R.id.menuitem1, R.id.menuitem2
  • This is because when we were adding the menu items from java we were assigning it an ItemId. That allowed Android to identify the menu item uniquely. But here the id assigned is menuitem1, menuitem2 etc. Hence we reference them using R.id.menuitem1, R.id.menuitem2 etc.

img4

COMPLETE SOURCE CODE

MainActivity.java

[java]
package com.nero.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(getApplicationContext(), “MenuItem1 selected”, Toast.LENGTH_LONG).show();
return true;
case R.id.menuitem2:
Toast.makeText(getApplicationContext(), “MenuItem2 selected”, Toast.LENGTH_LONG).show();
return true;
}
return super.onContextItemSelected(item);
}

}

[/java]

main.xml(<yourprojectname> -> res -> menu -> main.xml)

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menuitem1"
        android:title="MenuItem1"
        android:icon="@drawable/menuitemicon1" />

    <item
        android:id="@+id/menuitem2"
        android:title="MenuItem2"
        android:icon="@drawable/menuitemicon2" />

</menu>

Android development primer: Creating Options Menu in Android – Part III

Till now we have seen how to create and customize our Options Menu. In this post I will show you how to actually make use of the Options Menu to do something i.e. how to handle the clicks on Menu Items.

I will continue with the code from the previous post. Complete Source Code is at the bottom.

  • The function we will be overriding here is, onOptionsItemSelected() from android.app.activity class.
  • We will be using Toast so I would recommend you get a brief idea about what a Toast is and what it looks like from here. I will explain the different components of the Toast syntax in a while.
  • Write the following code below the onCreateOptionsMenu() method or onPrepareOptionsMenu() if you have one.[java]
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 1:
    Toast.makeText(getApplicationContext(), “MenuItem1 selected”, Toast.LENGTH_LONG).show();
    return true;
    case 2:
    Toast.makeText(getApplicationContext(), “MenuItem2 selected”, Toast.LENGTH_LONG).show();
    return true;
    }
    return super.onContextItemSelected(item);
    }
    [/java]
  • Save and execute the application in an emulator/device

part3-2   Part3-1

Here’s a little explanation for the Toast syntax.

  • getApplicationContext() : It returns the context for the whole application. It is used in order to get the context tied to the life cycle of the complete application and not some particular activity.
  • <char_sequence_of_your_choice> : This is the text to be displayed in the Toast.
  • Toast.LENGTH_LONG/Toast.LENGTH_SHORT : This defines the time for which the Toast should be visible.
  • show() : Everything to the left of show() is used to create the Toast. Once created it needs to be displayed. The show() method serves this purpose

Here I have shown you how to create a Toast on the click of a menu item. You can extend this to do practically anything you want like showing dialogs, creating notifications, retrieving data from databases etc.

COMPLETE SOURCE CODE

[java]
package com.nero.myfirstapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 1, 0, “MenuItem1”).setIcon(R.drawable.menuitemicon1);
menu.add(0, 2, 0, “MenuItem2”).setIcon(R.drawable.menuitemicon2);
return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Toast.makeText(getApplicationContext(), “MenuItem1 selected”, Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(getApplicationContext(), “MenuItem2 selected”, Toast.LENGTH_LONG).show();
return true;
}
return super.onContextItemSelected(item);
}

}

[/java]