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

We can have Options Menu in Android activities. Options Menu is the one that appears when the Menu button on the device is pressed. Many applications do nothing on the press of the button. These applications do not have an Options Menu configured. In this post I’ll show you how to have an Options Menu and I’ll do this using Java. Remember that this can also be done using XML, but programming in Java is far more intuitive and also because well, I know very little xml 😛
The image below shows the Menu Button on an Eclair AVD.

Capture

You know the drill. Create a new project, switch over to MainActivity.java that inherits from android.app.activity, and start coding. Complete Source Code is at the bottom.

  • If you are using the newer versions of SDK, you can already see the function onCreateOptionsMenu(Menu menu)
  • We will be overriding the original function in the Activity class to customize our menu.
  • If you run the skeleton application on the emulator and click the Menu button, a menu will pop up with only one option Settings. Depending on the SDK you are using this may or may not appear.
  • The menu has been already customized. You can see the following line in the method onCreateOptionsMenu(Menu menu).[java]
    getMenuInflater().inflate(R.menu.main, menu);
    [/java]
  • You can look at the predefined layout by navigating to <yourprojectname> -> res -> menu -> main.xml in Eclipse. For the time being, we will not be editing this xml and concentrate on working with Java.
  • Comment out getMenuInflater().inflate(R.menu.main, menu); and insert the below code.[java]
    menu.add(0, 1, 0, "MenuItem1");
    menu.add(0, 2, 0, "MenuItem2");
    [/java]
  • MenuItem1 and MenuItem2 are placeholders. Change them as you like. The syntax of the menu.add() function used here is[java]
    public abstract MenuItem add(int groupId, int itemId, int order, CharSequence title).
    [/java]

    Remember that this is an overloaded function, but we will be using the one specified above for the time being.

  • Save it and execute it on the emulator/device.

img3

Want to make your menu fancier? Keep reading.

You can insert images/icons to you menu items. A point to note however, is that the resolution of the icon should be pretty small so that it can appear over the menu item text. I would suggest one about the dimensions of 48×48.

  • Edit the lines you have just added, to read the following:
    [java]
    menu.add(0, 1, 0, "MenuItem1").setIcon(R.drawable.menuitemicon1);
    menu.add(0, 2, 0, "MenuItem2").setIcon(R.drawable.menuitemicon2);
    [/java]
  • Obviously, your drawable folders must have images that have menuitemicon1.png and menuitemicon2.png for their names.

img4

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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

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

@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);
menu.add(0, 1, 0, "MenuItem1").setIcon(R.drawable.menuitemicon1);
menu.add(0, 2, 0, "MenuItem2").setIcon(R.drawable.menuitemicon2);
return true;
}
}
[/java]

Largest Sum Contiguous Subarray

We have a sequence of integers and we need the maximum sum from the continuous sub-sequences.

Example-

Let the sequence of integers be (3,-4,5,-7,8,-6,21,-14,-9,19).
Then,the sub-array or sub-sequence with maximum sum is (8,-6,21) and the maximum sum is 23.

Brute Force-

We can check sums of all sequences of different sizes from 1 to N.Its complexity will be O(N^2).

Code-
[cpp]
//arr[1…N] contains the given integers
for(i=1;i<N;i++)
{
s=0;
for(j=i;j<N;j++)
{
s=s+arr[j];
if(s>max) max=s;
}
}
[/cpp]
‘max’ gives the value of the maximum sum.

Efficient code-

Formulation of linear recurrence-

Let S[i] be the maximum sum of a sequence that starts with any index and ends at i.
Then,

S[i] = max (S[i-1]+arr[i],arr[i]);

Maximum of all the values of S[1…N] gives the value of the maximum sum from the continuous sub-sequences.

Example-

arr[]={2,3,-4,5}
S[1]=2;
S[2]=max(S[1]+arr[2],arr[2])=5
S[3]=max(S[2]+arr[3],arr[3])=1
S[4]=max(S[3]+arr[4],arr[4])=6

Thus,the result is max of (S[1],S[2],S[3],S[4]) which is 6.

Its time complexity is O(N).

Code-

[cpp]
S[1]=arr[1];
result=S[1];
for(i=2;i<=N;i++)
{
S[i]=std::max( S[i-1]+arr[i], arr[i] );
if(S[i]>result) result=S[i];
}
[/cpp]

NOTE– This algorithm is similar to Kadane’s algorithm.

Subarray with given sum

Given a list of integers,our task is to find if a sub-sequence which adds to a given number exists or not.

Example-

The given list is (1,4,20,5,5) and the given number or sum is 29.
Then,the sub-sequence which adds to 29 is (4,20,5).

Brute Force-

All the sub-sequences are considered and its sum is compared with the given value.Its time complexity is O(N^2).

Code-

[cpp]

//arr[0…N-1] contains the given integers
// and the given number is X.
for(i=0;i<N;i++)
{
s=arr[i];
for(j=i+1;j<N;j++)
{
s=s+arr[j];
if(s==X) return 1; // sub array found
}
}
return 0; //sub-array not found
[/cpp]

Efficient Code-

Algorithm-

1. Initialize a variable curr_sum as first element.
2. Start from the second element and add all elements one by one to the curr_sum.
3. If curr_sum becomes equal to X, then a sub-sequence/sub-array is found.
4. If curr_sum exceeds X, then remove trailing elements one by one until curr_sum is less than X.

Its time complexity is O(N).

Code-

[cpp]
{
curr_sum=arr[0];
start=0;

for (i = 1; i <= n; i++)
{
// If curr_sum exceeds X, then
// remove the starting elements

while (curr_sum > X && start < i-1)
{
curr_sum = curr_sum – arr[start];
start++;
}

// If curr_sum becomes equal to X,
// then return true

if (curr_sum == X)
{
return 1; //sub-array found
}

// Add this element to curr_sum

if (i < n)
curr_sum = curr_sum + arr[i];
}
return 0; //sub-array not found
}

[/cpp]

Android development primer: Looking into Eclipse IDE

This post is aimed at giving you a little idea about what Eclipse IDE is and how you can use it’s features to the fullest for relatively faster coding. This is based strictly on it’s use in Android Development.

  • Eclipse is a multi-language Integrated Development Environment.
  • In it’s primitive form it is mostly used for writing Java programs.
  • It can be used, with the help of various plug-ins, to develop applications in an array of languages. Some of the most widely used ones are C, C++, PHP and Python.
  • If we are not speaking strictly, we can say it is similar to any WYSIWYG editor.

If we look into what and how it can help us in Android Programming, a couple of striking features are present. They are described in layman terms.

XML ASSISTANCE

  • It allows developers having little or no knowledge of XML to create layouts.
  • It allows Dragging and Dropping of elements from Palette to the Layout. It adds the required source code to XML automatically.
  • It allows for changing the attribute values of elements from the Properties tab. The source code is edited to reflect the changes made.
  • If the attributes of a particular element is changed, it allows for reflection of the changes in all codes in a project where this element might have been referred. It saves the programmer both time and effort.
  • The elements can be added in different configurations depending on the type of Layout selected. While dragging and dropping, Eclipse understands this layout and places the elements accordingly. For instance, in Relative Layout it allows for attributes like android:toLeftOf and android:toRightOf etc. In Linear Layouts it doesn’t allows such attributes.
  • It also understands the orientation of layouts.

CODE HINTING

  • Code Hinting refers to a feature where the IDE guesses the commands you want to enter as soon as you enter a few letters and it presents you with suggestions.
  • Ctrl+Space in Windows and Cmd+Space in Mac is the default key combination for Code Hinting.
  • While typing long statements, hit the Code Hinting key combination and choose the suitable statement from the list of statements presented.
  • Based on the SDK you are using for Android, Eclipse tells you whether some functions and features are out of date. They are deprecated by Eclipse.
  • It shows warnings and errors progressively as you type in statements so you know whether you have got the syntax and function arguments correct.

Although these may not seem very useful or time-saving in the initial stages of development, but they save a lot of effort when you are in the later stages and every single code in your project consists of more than a hundred lines.

Android development primer: Multiple Screen Support for Android, using Intents

We saw that on creating an Android Application Project, a skeleton “Hello World” application is created. The “Hello World” module is always the first step to learning anything. I’m sure you did a Hello World program when you were learning your first programming language. Quite boring isn’t it? Well, let’s get a bit creative.

We will add a few elements to our application and see how they work.

Create a new application project or edit the Hello World Application. Open up the MainActivity.java file and activity_main.xml and get ready for some coding.

If you have a problem while adding code snippets to you code, please have a look at the complete code at the bottom.

In the activity_main.xml follow the below steps:

  • Drag and drop an EditText from the Palette on the left.
  • Drag and drop a Button from the Palette on the left.
  • Click on the EditText and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
  • Edit the Id attribute of the EditText to “@+id/et” and click Yes/OK on any dialog that appears. Remember the name.
  • Click on the Button and it’s properties should appear on the Properties tab to the right. If it doesn’t, Right Click->Show In->Properties.
  • Edit the Id attribute of the Button to “@+id/but” and click Yes/OK on any dialog that appears. Remember the name.
  • For now, leave the EditText and the Button in their respective places. We will concentrate on how to make them work and not how to place them in the layout.

Save the activity_main.xml.
Now follow the below steps carefully:

  • Navigate to <yourpackagename> -> src. Right Click on <com.yourname.yourappname> and select New -> Class.
  • You are creating a new Class. In the Name field enter Second.
  • In the Superclass browse and type Activity. Select the android.app.activity. This makes your class an Activity.
  • Hit Finish and you the class opens up.
  • Navigate to <yourpackagename> -> res -> layout. Right Click on <com.yourname.yourappname> and select New -> Android XML File.
  • Name it second and choose relative layout from the Root Element list.
  • Hit Finish and the XML file opens up.

In the Second.java file add the following code inside the class.

[java]
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}
[/java]

If you have read my previous posts you will know exactly what we are doing here.

Now open second.xml and follow the below steps:

  • Drag and drop a TextView and change the Id attribute to “@+id/tv”.
  • Enter in the Text attribute – “This is the second Activity.”

Save second.xml. Switch over to MainActivity.java and add the following code in the onCreate() function.

[java]
Button but = (Button) findViewById(R.id.but);
EditText et = (EditText) findViewById(R.id.et);
but.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,Second.class);
startActivity(intent);
}
}
);
[/java]


As you type in the first statement, you’ll notice that Eclipse places a small cross so as to indicate there is an error in that line. What is the error? We have not imported the Android Button widget in our activity and so Eclipse doesn’t know what we mean when we type in “Button”. Hit Ctrl+1 on your keyboard. This is a shortcut to bring up suggested fixes to the errors. Select Import ‘Button’ (android.widget). You will now see that the statement just after the ‘=’ symbol is now erroneous. Hit Ctrl+1 again and select Add cast to ‘Button’. This way we have used type casting and import statements with which you must already be familiar from your Java knowledge. Do the same for the EditText statement.

  • OnClickListener() :  This adds a listener to the button that triggers when it is clicked
  • OnClick() : Holds the set of instructions that need to be executed when the button is clicked
  • Intent : This is a very important feature of Android. For the time being, it’ll be sufficient for you to know that an Intent is used to call other Activities. We can also pass data using this across activities. We’ll see this in a while. The syntax of the constructor is new Intent(<currentactivityobject>, <destinationactivityclass>). The object of current activity is MainActivity.this and the class of the destination activity is Second.class.
  • startActivity() : It is used to start off a new activity while pushing the current one to the Back Stack. It takes an intent as an argument.

What we’ve done is we’ve added a button and configured it to fire the Second Activity when clicked. Run this application using the emulator. When the MainActivity is up and you click the button to go to the second Activity, your application will crash unexpectedly. Why? Because we have not added the Second activity to the AndroidManifest.xml file.

How do you get to know what went wrong? Well, here’s how. On the top right you can see Java and DDMS. DDMS (Dalvik Debug Monitor Server) tells you exactly what went wrong. Click on it and scroll to the top of the group of lines in red. You will see ActivityNotFoundException. It also says – “Have you declared this activity in your AndroidManifest.xml?”. So that’s how we know that we haven’t declared the Second activity in the Android Manifest file.

The Android Manifest file needs to recognize each and every activity in your application.

  • Open up AndroidManifest.xml file from the project contents list and from the tabs at the bottom select AndroidManifest.xml
  • Just before </application> add this – <activity android:name=”.Second” />
  • Save.

Launch the application again and this time it should work just fine. 🙂

You must be wondering why we did not make use of the EditText that we added to the layout. I told you before that we can send data across activities using Intents. That is preciseld what this EditText is for. Here we go.

  • Add this line in the MainActivity.java before the startActivity() function :-
    [java]
    intent.putExtra("data", et.getText().toString());
    [/java]



  • Add the following lines in Second.java after the setContentView() function :
    [java]
    TextView tv = (TextView) findViewById(R.id.tv);
    tv.setText(getIntent().getStringExtra("data"));
    [/java]

As you can see we can set the text to be displayed in the TextView from java too and this takes precedence over the xml.
What we have done here is that we will be displaying whatever text the user enters in the MainActivity in the Second Activity. Launch the application and see it work.

img1    img2

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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

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 EditText et = (EditText) findViewById(R.id.et);
but.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(Main.this,Second.class);
intent.putExtra("data", et.getText().toString());
startActivity(intent);
}
});
}
@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]

Second.java

[java]
package com.nero.myfirstapp;

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 Second extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(getIntent().getStringExtra("data"));
}
}
[/java]

activity_main.xml

second.xml

AndroidManifest.xml

Binary Search

This is a short note on using binary search, in continuance of my series on Algorithms.

Suppose we have to find whether a particular element exists in the sorted list of N numbers or not.
Let “arr” be the array which contains the N elements and the element to be searched is “key”.
Then, the time complexity using brute force will be O(N).

CODE-

[cpp]

for(i=0;i<N;i++)
{
if(arr[i]==key)
{
printf("Element is found\n");break;
}
}

[/cpp]

But,using binary search,the time complexity will be O(log(N)).A binary search halves the number of items to be checked each time and thus has logarithmic complexity.

ALGORITHM-

In this algorithm,the key is compared with the middle element of the array.
Cases:
1.If the middle element is equal to the key,then the search is completed.
2.If the key is less than the middle element,then the algorithm is repeated on the sub-array to the left of the middle element.
3.If the key is greater than the middle element,then the algorithm is repeated on the sub-array to the right of the middle element.
4.If the remaining array to be searched is empty,then the key cannot be found in the array and the search is completed.

CODE-

Recursive solution-

[cpp]
int binarysearch(int arr[],int key,int beg,int last)
{

// beg and last indicate the starting and ending indices of the subarray.
// Initially,beg has the value 0 and last has the value n-1.</em>

if(beg >last) return 0; // key not found</em>

else
{
int mid=(beg+last)/2; // finding the middle element</em>

if(key==arr[mid])return 1; // key found</em>

else if(key < arr[mid]) return binarysearch(arr,key,beg,mid-1);

else
return binarysearch(arr,key,mid+1,last);
}
}
[/cpp]

NOTE- Binary Search is used only when the given list is sorted.If the list is unordered,brute force is better as sorting will have a complexity of O(N*log(N)).

Linux intro and Basic commands

Linux is a Unix-like computer operating system. Linux was originally developed as a free operating system for Intel x86-based personal computers. Now its popular on PCs, tablets, smart phones,  and is a leading operating system on servers and other big iron systems such as mainframe computers and supercomputers.

Best Linux quotes–

“The box said ‘Required Windows 95 or better’. So, I installed LINUX.”
“A Windows user spends 1/3 of his life sleeping, 1/3 working, 1/3 waiting.”
“We all know Linux is great, it does infinite loops in 5 seconds.”
“Avoid the Gates of Hell. Use Linux.”
“..Linux really *is* the best thing since sliced bread.”
“Linux: the operating system with a CLUE, Command Line User Environment.”
“I develop for Linux for a living, I used to develop for DOS.Going from DOS to Linux is like trading a glider for an F117.”

Advantages of LINUX over Windows–

Cost– Linux is available free (as in free food) !
Security– Linux is perceived as more safe that Windows. Which means Linux does not require any anti-virus which again reduces comparative cost even further.
Open Source – With Linux technically, you have the power to control just about every aspect of the operating system.
Software on Linux tends to be packed with more features and greater usability than software on Windows.

Although Linux is as user friendly and intuitive to use as Windows, it will help programmers if they know the basic Linux commands.

This blog lists all those commands for LINUX based FILE system that a beginner should know. These are the basic commands which are generally asked on Linux usage in the interviews too.

1. pwd – To view the present working directory.
2. mkdir directory_name – To create a new directory in the present working directory.
3. cd – To change working directory. Example- cd /home/new/help
4. ls -l -To list the files as well as directories present in the particular working directory.
5. ls -la – It lists the hidden files or directories as well.
6. touch file_name.ext – To create a new file with a name and extension.Extension is not necessary.
7. cat file_name – To view the contents of the file.
8. vi file_name – To insert data in the file.After entering this command,press I and then type the data you want to enter.To quit,command is ‘ :wq ‘.
9. rm file_name – To remove an empty file.
10. rmdir directory_name – To remove an empty directory.
11. rmdir -r directory_name – To remove a directory which contains subdirectories or files.’r’ stands for recursion.
12. clear – To clear the screen.Shortcut is Ctrl+L.
13. useradd user_name – To add a new user.
14. passwd user_name– To change the existing password of a user.
15. groupadd group_name – To add a new group. Many users form a single group.
16. userdel user_name – To delete a user.
17. groupdel group_name -To delete a group.
18. cp source_path destination_path– To copy something in a file or directory.Example of source path or destination path – /home/mango/abcd.txt
19. mv source_path destination_path – To move something in a file or directory.
20. su – user_name – To switch from one user to another user.

MASTER command—

command_name info – To view the information about any command.Example: mkdir info

Android development primer: Layout elements in Android

I’m sure when you look at the Graphical Layout of any xml file in Android, what catches your attention more than the layout itself is the long list of elements on the left, called Palette. Well, here’s a list of a few frequently used Layout elements and their functions.

FORM WIDGETS

  • TextView Large/Medium/Small : This element is used to display a static text in the layout. It is available in three sizes Large, Medium and Small.
  • Button/Small Button : Well, it’s a button. Just like buttons on webpages are required to achieve a certain tasks, so it is used here. Although in reality a button is touched in an Android device to trigger it’s function, we’ll be referring it as a click hereafter.
  • CheckBox : If you want your users to have options from which they can select more than one, you are going to need checkboxes.
  • RadioButton : If you want your users to have options from which they can select only one, you are going to need radio buttons.
  • ProgressBar Large/Small/Horizontal : It is a progress bar that you might require if your application is in the middle of something and a screen staring at the user in the meantime, is just not your style.

TEXT FIELDS

  • All this field contains, is lots and lots of EditText. An EditText is used to create a text field where the user can provide a written input.
  • There are various types of EditTexts. They differ in their “Input Type” i.e. the type of value that can be entered in them.

LAYOUTS

This field contains various types of layouts. A layout can be nested within another to achieve desired UI.

  • LinearLayout Vertical/Horizontal : This allows elements within it to be added linearly.
  • RelativeLayout : This allows elements within it to be added relatively to other elements.
  • GridLayout : It is used to achieve a grid like UI.

COMPOSITE

  • ListView : This is a rather widely used element. It helps display a number of items in a list in the layout.
  • GridView : This presents a grid like view of elements. This is not at all related to GridLayout.
  • ScrollView/Horizontal Scroll View : Sometimes it is required to limit the size of a layout to a certain value. However it’s content might be more than what can be accommodated in it. ScrollView is used here so that the content can be scrolled.
  • SearchView : This allows searching. You must have seen a Google SearcView in an Android device.
  • SlidingDrawer : This is a neat and a handy element in many situations. It is a drawer that can be opened and closed with clicks. This can be put over the layout of an activity.

IMAGES AND MEDIA

  •  ImageView : It is a view in which you can put in an image.
  • ImageButton : It is an image and also a button. A rather fancy way to have a button, eh?
  • Gallery : It is a view that can have more than one picture and hence is a gallery.

TIME AND DATE

  • TimePicker : Sometimes when in your application you need the user to enter a time, a TimePicker can do that neatly. Good old EditText can serve the purpose too, but TimePicker is much more fancy and easy to work with.
  • DatePicker : Just like TimePicker, DatePicker is used to pick a date.

TRANSITIONS

  • It deals with animations that can be used while transitions between layouts occur.

ADVANCED

  • NumberPicker : Just like TimePicker and DatePicker, this is used to pick numbers.
  • ZoomButton/ZoomControls : Used to control zoom in/zoom out operations mainly in galleries.

These elements are used most frequently. There are a bunch of other elements that are present. Keep adding them to your layout and experimenting!!

Android development primer: Creating your first Android Application

So now that you have a little idea what Android is all about, we will create our very first Android Project.

Launch Eclipse IDE. Navigate to File->New->Android Application Project. The “New Android Application” dialog comes to the front.

Depending on the version of Eclipse and Android SDK you are using, some options may or may not be present and some might be distributed over a number of dialogs.

  • Project Name is the name of the project you want your application to be in.
  • Application Name is the name of the application. This is the name by which your application will be installed in users’ devices.
  • Package Name is the package in which your application resides. It often looks something like “com.example.yourappname” and automatically appears once you put in the Application Name. You can choose to edit it or leave it be. Usually developers replace “example” with their name.
  • Minimum Required SDK  or Min SDK Version shows the lowest Android version that your application supports. For instance if you set this to API 9 (Gingerbread), devices with API 1-8 will not be able to install your application. It is generally advisable to use as low an API as possible. But then there arises a problem that you will not be able to include features or elements that have been introduced in the later versions. You need to analyze this trade-off and choose this accordingly.
  • Target SDK or Build Target is the version of Android that your applications targets.
  • Compile With should generally be the same as Target SDK.
  • Theme shows the basic theme that you want your application to have. Choose whichever suits your needs.
  • Create Activity is to be checked and the name of an activity to be provided. Usually, this is the activity that appears when your applications is launched and is named Main or MainActivity.
  • If you have the latest versions of Android SDK you will be taken to a number of dialogs from here where you can select the icon of your application, navigation type etc. Since it is our first application, we will let them be at their default values.
  • When you are done Click Finish.

Now to the left of your coding area, you can see a “Package Explorer” tab that lists all packages your workspace contains. You package sould be visible in this area.

If you can see a small cross in the icon of you project, don’t worry. Android needs a little time to set itself up, after which the cross vanishes. In fact all packages will have this cross every time you launch Eclipse.

UNDERSTANDING THE SKELETON APPLICATION.

You have just created an Android Application Project. In order to assist you Android creates a “Hello World” skeleton application on it’s own. Navigate to <yourprojectname> -> src -> <com.yourname.yourappname> -> Main.java. In newer SDKs Main.java is named MainActivity.java. Once this opens up, take a good look at the source code. If you have prior java experience, you can see some familiar things. You can see the import packages, class name and the parent class name from which this class is inherited. You can also see some functions/methods in the source code. Below is the explanation of all the elements of the source code.

  • import android.app.activity : This is the Android Activity package. This package contains all the functions that one can possibly use in an Activity.
  • public class MainActivity extends Activity : Each activity in your application will be in the form of a Class. This class inherits from the Class Activity. This class/activity hence should override the required functions of the original class.
  • onCreate() : This is the function that is called when an activity is first created. This takes an argument Bundle savedInstanceState. For the time being, it will be sufficient for you to know that the state of an activity is saved in a Bundle. We will get into further details later.
  • super.onCreate() : This calls the onCreate() method of the super class i.e. the Activity class with the same arguments.
  • setContentView() : This assigns a layout to the Activity. The argument to this function is R.layout.activity_main. We’ll come to it in a minute.

So, when the activity is first created a couple of things are done. The super class method is called and a layout is assigned to the activity. There are many other functions such as onPause(), onStart(), onResume() etc. in order to monitor the life-cycle of an activity. We’ll discuss this in detail at a later time.
In order to understand what a layout is navigate to yourprojectname -> res -> layout. You can now see the “activity_main.xml” file. In some systems it might be named “main.xml”. This is the layout of your activity. Open it and have a look at the source code.

  • You can see that there are two tabs at the bottom – Graphical Layout and activity_main.xml
  • The Graphical Layout shows what your layout would look like in the device/emulator.
  • activity_main.xml shows the xml code of the layout.

Depending on the version of SDK some of the below components may or may not be present in your xml code.

  • LinearLayout : It tells you that all the components in your layout will be laid down in a linear fashion i.e. one below the other.
  • RelativeLayout : It tell you that all the components in your layout will be laid down in a relative fashion i.e. you can choose the height and width of it’s location from the axes.
  • TextView : This is a rather widely used component in applications. It is used to create static text in an application.

You can also see some properties inside the tags in the xml code. Here’s a brief description of them

  • layout_width/height determines the width and height respectively of the particular element. match_parent/fill_parent means that it covers the entire width/height of it’s parent layout i.e. the layout it is inside of. wrap_content means that it only occupies the space that it requires.
  • margin_top/bottom/left/right determines the margin between two components or the borders of the screen
  • orientation determines the orientation in which elements will be added within this layout. If the orientation is horizontal elements will be added side-by-side. It is mainly a feature of Linear Layout.
  • text is present in the textview. It determines the text that the textview is to show on the screen.

So, now that you are familiar with the skeleton application that Android provided you with, it is time to see how it will look like in a device. For this we will use an AVD that we have previously created. If you haven’t created an AVD create one now.
Click the “Run” button which will pop up a dialog box in which you should select Android Application. This dialog appears only the first time an activity of an application is run. If the emulator was already running when you ran the application it installs on your emulator and if not, the most suitable emulator from your created AVDs is selected and launched. Once the application is installed it runs automatically. You can see the “Hello World, Main!” message on the screen.

Although this is a basic way to get started with an application, I’m gonna go ahead and tell you a couple of things that might interest you. Navigate to <yourprojectname> -> gen -> R.java.
Caution : Take care not to edit the contents of R.java file as it is an Auto-Generated file by the Android system.
Let’s look at how things work

  • With every resources that you add to your project (resources reside in <yourprojectname> -> res) Android is going to add an entry to the R.java file.
  • drawable/layout/string are all resources that you can see in <yourprojectname> -> res. You can now understand why the argument in the setContentView() is R.layout.activity_main.
  • In order to refer to each resource, Android assigns a numerical value that is represented in the hexadecimal form.

Another interesting thing is the res folder. It contains all the resources that your application might need.

  • drawable hdpi/ldpi/mdpi/xhdpi/xxhdpi : These contain the pictures or icons that you have in your applications. In order to put an icon in you application, navigate to <eclipseworkspacelocation> -> <yourprojectname> -> res -> drawablehdpi, paste the icon in it and from your code refer to it as R.drawable.<youriconname>
  • You can choose to have the same icon in different resolutions for devices that have hdpi/ldpi/mdpi/xdhpi/xxhdpi screens.
  • You can also see values folder in the “res” folder. It contains dimens.xml, strings.xml, styles.xml. Click on each one and have a look at the source code.

Now, that you have an idea how to create an application, I will discuss about the elements of the layout and multiple screen support in my later posts.

Best Code to find n to the power k(n^k)

To find n^k,using brute force,

ALGORITHM-
Initialize result to 1.
Iterate from 1 to k and multiply n to result.
Return result.

CODE-

result=1;
for(i=1;i<=k;i++)
{
result=result*n;
}

Complexity for this code is O(k).

Its not only about coding for a given task but also making the code efficient in terms of space as well as time.The above code will take a lot of time for computation for larger values of k.

Efficient code–

Complexity for this code is O(log(k)).

ALGORITHM-

power (n,k)
{

if (k==0)
return 1;

if (k is even)
return (power(n,k/2) * power (n,k/2) );

else if (k is odd)
return (power (n,k/2) * power (n,k/2) * n );

}

CODE-

result=1;
while(k)
{
if(k%2!=0){result=result*n;}
n=n*n;
k=k/2;
}