0% found this document useful (0 votes)
82 views

Android

1. The document describes how to create a simple "Hello World" Android application in 3 steps: creating a new Android project, writing a message in the XML layout file, and running the Android application. 2. It provides details on setting up the project structure, including configuring the activity, writing code in Java and XML files, and generating the APK file. 3. It also discusses some internal details like the Dalvik Virtual Machine, resources, and the manifest file.

Uploaded by

Suman Das
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Android

1. The document describes how to create a simple "Hello World" Android application in 3 steps: creating a new Android project, writing a message in the XML layout file, and running the Android application. 2. It provides details on setting up the project structure, including configuring the activity, writing code in Java and XML files, and generating the APK file. 3. It also discusses some internal details like the Dalvik Virtual Machine, resources, and the manifest file.

Uploaded by

Suman Das
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 79

https://www.javatpoint.

com/android-hide-title-bar-example

How to make android apps


In this page, you will know how to create the simple hello android application. We are creating
the simple example of android using the Eclipse IDE. For creating the simple example:

1. Create the new android project


2. Write the message (optional)
3. Run the android application

Hello Android Example

You need to follow the 3 steps mentioned above for creating the Hello android application.

1) Create the New Android project

For creating the new android studio project:

1) Select Start a new Android Studio project

2) Provide the following information: Application name, Company domain, Project location and Package
name of application and click next.

1
3) Select the API level of application and click next.

4) Select the Activity type (Empty Activity).

2
5) Provide the Activity Name and click finish.

3
After finishing the Activity configuration, Android Studio auto generates the activity class and
other required configuration files.

Now an android project has been created. You can explore the android project and see the simple
program, it looks like this:

4
2) Write the message

File: activity_main.xml

Android studio auto generates code for activity_main.xml file. You may edit this file according
to your requirement.

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


2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.co
m/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="first.javatpoint.com.welcome.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
5
11. android:layout_height="wrap_content"
12. android:text="Hello Android!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>
19. }

File: MainActivity.java

1. package first.javatpoint.com.welcome;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. }
12. }

3) Run the android application

To run the android application, click the run icon on the toolbar or simply press Shift + F10.

The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting the
emulator, the android studio installs the application and launches the activity. You will see something like
this:

6
The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting the
emulator, the android studio installs the application and launches the activity. You will see something like
this:

Hello Android

Internal Details of Hello Android Example


Here, we are going to learn the internal details or working of hello android example.

Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc. Let's understand the project structure of android application.

7
Java Source Code

Let's see the java source file created by the Eclipse IDE:

File: MainActivity.java

1. package com.example.helloandroid;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.widget.TextView;
6. public class MainActivity extends Activity {//(1)

8
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {//(2)
9. super.onCreate(savedInstanceState);
10.
11. setContentView(R.layout.activity_main);//(3)
12. }
13. @Override
14. public boolean onCreateOptionsMenu(Menu menu) {//(4)
15. // Inflate the menu; this adds items to the action bar if it is present.
16. getMenuInflater().inflate(R.menu.activity_main, menu);
17. return true;
18. }
19. }

(1) Activity is a java class that creates and default window on the screen where we can place
different components such as Button, EditText, TextView, Spinner etc. It is like the Frame of
Java AWT.

It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.

(2) The onCreate method is called when Activity class is first created.

(3) The setContentView(R.layout.activity_main) gives information about our layout


resource. Here, our layout resources are defined in activity_main.xml file.

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity" >

9
<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

</RelativeLayout>

As you can see, a textview is created by the framework automatically. But the message for
this string is defined in the strings.xml file. The @string/hello_world provides information
about the textview message. The value of the attribute hello_world is defined in the
strings.xml file.

File: strings.xml

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

<resources>

<string name="app_name">helloandroid</string>

<string name="hello_world">Hello world!</string>

<string name="menu_settings">Settings</string>

</resources>

You can change the value of the hello_world attribute from this file.

It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.

File: R.java

/* AUTO-GENERATED FILE. DO NOT MODIFY.

* This class was automatically generated by the


10
* aapt tool from the resource data it found. It

* should not be modified by hand.

*/

package com.example.helloandroid;

public final class R {

public static final class attr {

public static final class drawable {

public static final int ic_launcher=0x7f020000;

public static final class id {

public static final int menu_settings=0x7f070000;

public static final class layout {

public static final int activity_main=0x7f030000;

public static final class menu {

public static final int activity_main=0x7f060000;

public static final class string {

public static final int app_name=0x7f040000;

public static final int hello_world=0x7f040001;

public static final int menu_settings=0x7f040002;

11
}

public static final class style {

/**

Base application theme, dependent on API level. This theme is replaced

by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

Theme customizations available in newer API levels can go in

res/values-vXX/styles.xml, while customizations related to

backward-compatibility can go here.

Base application theme for API 11+. This theme completely replaces

AppBaseTheme from res/values/styles.xml on API 11+ devices.

API 11 theme customizations can go here.

Base application theme for API 14+. This theme completely replaces

AppBaseTheme from BOTH res/values/styles.xml and

res/values-v11/styles.xml on API 14+ devices.

API 14 theme customizations can go here.

*/

public static final int AppBaseTheme=0x7f050000;

/** Application theme.

All customizations that are NOT specific to a particular API-level can go here.

*/

public static final int AppTheme=0x7f050001;

12
APK File

An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it.

Resources

It contains resource files including activity_main, strings, styles etc.

Manifest file

It contains information about package including components such as activities, services, content
providers etc.

For more information about manifest file visit here: AndroidManifest.xml file.

Dalvik Virtual Machine | DVM


As we know the modern JVM is high performance and provides excellent memory management.
But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file.

Let's see the compiling and packaging process from the source file:

13
The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging process.

AndroidManifest.xml file in android


The AndroidManifest.xml file contains information of your package, including components of
the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

 It is responsible to protect the application to access any protected parts by providing


the permissions.
 It also declares the android api that the application is going to use.
 It lists the instrumentation classes. The instrumentation classes provides profiling and
other informations. These informations are removed just before the application is
published etc.

This is the required xml file for all the android application and located inside the root directory.

A simple AndroidManifest.xml file looks like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
14
package="com.javatpoint.hello"

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>

15
</manifest>

Elements of the AndroidManifest.xml file

The elements used in the above xml file are described below.

<manifest>

manifest is the root element of the AndroidManifest.xml file. It has package attribute that
describes the package name of the activity class.

<application>

application is the subelement of the manifest. It includes the namespace declaration. This
element contains several subelements that declares the application component such as activity
etc.

The commonly used attributes are of this element are icon, label, theme etc.

android:icon represents the icon for all the android application components.

android:label works as the default label for all the application components.

android:theme represents a common theme for all the android activities.

<activity>

activity is the subelement of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required attribute.

<intent-filter>

intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.

<action>

It adds an action for the intent-filter. The intent-filter must have at least one action element.

16
<category>

It adds a category name to an intent-filter.

Android R.java file


Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains
resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any
action on the component.

Let's see the android R.java file. It includes a lot of static nested classes such as menu, id, layout,
attr, drawable, string etc.

/* AUTO-GENERATED FILE. DO NOT MODIFY.

* This class was automatically generated by the

* aapt tool from the resource data it found. It

* should not be modified by hand.

*/

package com.example.helloandroid;

public final class R {

public static final class attr {

public static final class drawable {

public static final int ic_launcher=0x7f020000;

}
17
public static final class id {

public static final int menu_settings=0x7f070000;

public static final class layout {

public static final int activity_main=0x7f030000;

public static final class menu {

public static final int activity_main=0x7f060000;

public static final class string {

public static final int app_name=0x7f040000;

public static final int hello_world=0x7f040001;

public static final int menu_settings=0x7f040002;

public static final class style {

/**

Base application theme, dependent on API level. This theme is replaced

by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

Theme customizations available in newer API levels can go in

res/values-vXX/styles.xml, while customizations related to

backward-compatibility can go here.

18
Base application theme for API 11+. This theme completely replaces

AppBaseTheme from res/values/styles.xml on API 11+ devices.

API 11 theme customizations can go here.

Base application theme for API 14+. This theme completely replaces

AppBaseTheme from BOTH res/values/styles.xml and

res/values-v11/styles.xml on API 14+ devices.

API 14 theme customizations can go here.

*/

public static final int AppBaseTheme=0x7f050000;

/** Application theme.

All customizations that are NOT specific to a particular API-level can go here.

*/

public static final int AppTheme=0x7f050001;

Android Hide Title Bar and Full Screen


Example

19
In this example, we are going to explain how to hide the title bar and how to display content in
full screen mode.

The requestWindowFeature(Window.FEATURE_NO_TITLE) method of Activity must be


called to hide the title. But, it must be coded before the setContentView method.

Code that hides title bar of activity

The getSupportActionBar() method is used to retrieve the instance of ActionBar class. Calling
the hide() method of ActionBar class hides the title bar.

requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title

getSupportActionBar().hide(); //hide the title bar

Code that enables full screen mode of activity

The setFlags() method of Window class is used to display content in full screen mode. You need
to pass the WindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags
method.

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN); //show the activity in full


screen

Android Hide Title Bar and Full Screen Example

Let's see the full code to hide the title bar in android.

activity_main.xml
File: activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

20
android:layout_height="match_parent"

tools:context="first.javatpoint.com.hidetitlebar.MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Activity class
File: MainActivity.java

package first.javatpoint.com.hidetitlebar;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Window;

import android.view.WindowManager;

public class MainActivity extends AppCompatActivity {

21
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title

getSupportActionBar().hide(); // hide the title bar

this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,

WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen

setContentView(R.layout.activity_main);

Android Screen Orientation Example


The screenOrientation is the attribute of activity element. The orientation of android activity
can be portrait, landscape, sensor, unspecified etc. You need to define it in the
AndroidManifest.xml file.

Syntax:

<activity android:name="package_name.Your_ActivityName"

android:screenOrientation="orirntation_type">

</activity>

Example:

<activity android:name=" example.javatpoint.com.screenorientation.MainActivity"

android:screenOrientation="portrait">
22
</activity>

<activity android:name=".SecondActivity"

android:screenOrientation="landscape">

</activity>

The common values for screenOrientation attribute are as follows:

Value Description
unspecified It is the default value. In such case, system chooses the orientation.
Portrait taller not wider
landscape wider not taller
sensor orientation is determined by the device orientation sensor.

Android Portrait and Landscape mode screen orientation example

In this example, we will create two activities of different screen orientation. The first activity
(MainActivity) will be as "portrait" orientation and second activity (SecondActivity) as
"landscape" orientation type.

activity_main.xml
File: activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="example.javatpoint.com.screenorientation.MainActivity">

23
<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="8dp"

android:layout_marginTop="112dp"

android:onClick="onClick"

android:text="Launch next activity"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.612"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/editText1"

app:layout_constraintVertical_bias="0.613" />

<TextView

android:id="@+id/editText1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:layout_marginTop="124dp"

24
android:ems="10"

android:textSize="22dp"

android:text="This activity is portrait orientation"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.502"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Activity class

File: MainActivity.java

package example.javatpoint.com.screenorientation;

import android.content.Intent;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button button1;

@Override

protected void onCreate(Bundle savedInstanceState) {

25
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button1=(Button)findViewById(R.id.button1);

public void onClick(View v) {

Intent intent = new Intent(MainActivity.this,SecondActivity.class);

startActivity(intent);

activity_second.xml
File: activity_second.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="example.javatpoint.com.screenorientation.SecondActivity">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"
26
android:layout_height="wrap_content"

android:layout_marginEnd="8dp"

android:layout_marginStart="8dp"

android:layout_marginTop="180dp"

android:text="this is landscape orientation"

android:textSize="22dp"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.502"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

SecondActivity class
File: SecondActivity.java

package example.javatpoint.com.screenorientation;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

27
setContentView(R.layout.activity_second);

AndroidManifest.xml
File: AndroidManifest.xml

In AndroidManifest.xml file add the screenOrientation attribute in activity and provides its
orientation. In this example, we provide "portrait" orientation for MainActivity and "landscape"
for SecondActivity.

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

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

package="example.javatpoint.com.screenorientation">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity

android:name="example.javatpoint.com.screenorientation.MainActivity"

android:screenOrientation="portrait">

<intent-filter>

28
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity android:name=".SecondActivity"

android:screenOrientation="landscape">

</activity>

</application>

</manifest>

Android Widgets
There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.

Android widgets are easy to learn. The widely used android widgets with examples are given
below:

Android Button

Let's learn how to perform event handling on button click.

Android Toast

Displays information for the short duration of time.

Custom Toast

We are able to customize the toast, such as we can display image on the toast

ToggleButton

It has two states ON/OFF.


29
CheckBox

Let's see the application of simple food ordering.

AlertDialog

AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.

Spinner

Spinner displays the multiple options, but only one can be selected at a time.

AutoCompleteTextView

Let's see the simple example of AutoCompleteTextView.

RatingBar

RatingBar displays the rating bar.

DatePicker

Datepicker displays the datepicker dialog that can be used to pick the date.

TimePicker

TimePicker displays the timepicker dialog that can be used to pick the time.

ProgressBar

ProgressBar displays progress task.

Android Button Example

Android Button represents a push-button. The android.widget.Button is subclass of TextView


class and CompoundButton is the subclass of Button class.

There are different types of buttons in android such as RadioButton, ToggleButton,


CompoundButton etc.

30
Android Button Example with Listener

Here, we are going to create two textfields and one button for sum of two numbers. If user clicks
button, sum of two input values is displayed on the Toast.

We can perform action on button using different types such as calling listener on button or
adding onClick property of button in activity's xml file.

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

//code

});

<Button

android:onClick="methodName"

/>

Drag the component or write the code for UI in activity_main.xml

First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets
palette as shown in the following figure.

31
The generated code for the ui components will be like this:

File: activity_main.xml

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

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

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="example.javatpoint.com.sumoftwonumber.MainActivity">
32
<EditText

android:id="@+id/editText1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="61dp"

android:ems="10"

android:inputType="number"

tools:layout_editor_absoluteX="84dp"

tools:layout_editor_absoluteY="53dp" />

<EditText

android:id="@+id/editText2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/editText1"

android:layout_centerHorizontal="true"

android:layout_marginTop="32dp"

android:ems="10"

android:inputType="number"

tools:layout_editor_absoluteX="84dp"

33
tools:layout_editor_absoluteY="127dp" />

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/editText2"

android:layout_centerHorizontal="true"

android:layout_marginTop="109dp"

android:text="ADD"

tools:layout_editor_absoluteX="148dp"

tools:layout_editor_absoluteY="266dp" />

</RelativeLayout>

Activity class

Now write the code to display the sum of two numbers.

File: MainActivity.java

package example.javatpoint.com.sumoftwonumber;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

34
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText edittext1, edittext2;

private Button buttonSum;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

addListenerOnButton();

public void addListenerOnButton() {

edittext1 = (EditText) findViewById(R.id.editText1);

edittext2 = (EditText) findViewById(R.id.editText2);

buttonSum = (Button) findViewById(R.id.button);

buttonSum.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

String value1=edittext1.getText().toString();

35
String value2=edittext2.getText().toString();

int a=Integer.parseInt(value1);

int b=Integer.parseInt(value2);

int sum=a+b;

Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_L
ONG).show();

});

36
Output:

Android Toast Example


Andorid Toast can be used to display information for the short period of time. A toast contains
message to be displayed quickly and disappears after sometime.

The android.widget.Toast class is the subclass of java.lang.Object class.

You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.

Toast class

Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.

37
Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.

Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

public static Toast makeText(Context context, CharSequence makes the toast containing text and
text, int duration) duration.

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and vertical margin
verticalMargin) difference.

Android Toast Example

Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show(
);

Another code:

Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SH


ORT);

toast.setMargin(50,50);

toast.show();

Here, getApplicationContext() method returns the instance of Context.

Full code of activity class displaying Toast

Let's see the code to display the toast.

38
File: MainActivity.java

package example.javatpoint.com.toast;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//Displaying Toast with Hello Javatpoint message

Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).s
how();

39
Output:

Android Custom Toast Example


You are able to create custom toast in android. So, you can display some images like
congratulations or loss on the toast. It means you are able to customize the toast now.

activity_main.xml

Drag the component that you want to display on the main activity.

File: activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
40
xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="example.javatpoint.com.customtoast.MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

customtoast.xml

Create another xml file inside the layout directory. Here we are having ImageView and TextView
in this xml file.

File: customtoast.xml

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

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

android:layout_width="match_parent"

41
android:layout_height="match_parent"

android:id="@+id/custom_toast_layout"

android:orientation="vertical"

android:background="#F14E23"

>

<ImageView

android:id="@+id/custom_toast_image"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:contentDescription="Hello world"

android:src="@drawable/jtp_logo"/>

<TextView

android:id="@+id/custom_toast_message"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:contentDescription="To"

android:text="JavaTpoint custom Toast" />

</LinearLayout>

Activity class

Now write the code to display the custom toast.

42
File: MainActivity.java

package example.javatpoint.com.customtoast;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Gravity;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//Creating the LayoutInflater instance

LayoutInflater li = getLayoutInflater();

//Getting the View object as defined in the customtoast.xml file

View layout = li.inflate(R.layout.customtoast,(ViewGroup) findViewById(R.id.custom_


toast_layout));

43
//Creating the Toast object

Toast toast = new Toast(getApplicationContext());

toast.setDuration(Toast.LENGTH_SHORT);

toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

toast.setView(layout);//setting the view of custom toast layout

toast.show();

Output:

44
Android ToggleButton Example

Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.

It is beneficial if user have to change the setting between two states. It can be used to On/Off
Sound, Wifi, Bluetooth etc.

Since Android 4.0, there is another type of toggle button called switch that provides slider
control.

Android ToggleButton and Switch both are the subclasses of CompoundButton class.

Android ToggleButton class

ToggleButton class provides the facility of creating the toggle button.

45
XML Attributes of ToggleButton class

The 3 XML attributes of ToggleButton class.

XML Attribute Description

android:disabledAlpha The alpha to apply to the indicator when disabled.

android:textOff The text for the button when it is not checked.

android:textOn The text for the button when it is checked.

Methods of ToggleButton class

The widely used methods of ToggleButton class are given below.

Method Description

CharSequence getTextOff() Returns the text when button is not in the checked state.

CharSequence getTextOn() Returns the text for when button is in the checked state.

void setChecked(boolean checked) Changes the checked state of this button.

Android ToggleButton Example

activity_main.xml

Drag two toggle button and one button for the layout. Now the activity_main.xml file will look
like this:

File: activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

46
android:layout_height="match_parent"

tools:context="example.javatpoint.com.togglebutton.MainActivity">

<ToggleButton

android:id="@+id/toggleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="8dp"

android:layout_marginTop="80dp"

android:text="ToggleButton"

android:textOff="Off"

android:textOn="On"

app:layout_constraintEnd_toStartOf="@+id/toggleButton2"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

<ToggleButton

android:id="@+id/toggleButton2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginRight="60dp"

android:layout_marginTop="80dp"

android:text="ToggleButton"

47
android:textOff="Off"

android:textOn="On"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintTop_toTopOf="parent" />

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="144dp"

android:layout_marginLeft="148dp"

android:text="Submit"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

Activity class

Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java

package example.javatpoint.com.togglebutton;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

48
import android.widget.Button;

import android.widget.Toast;

import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

private ToggleButton toggleButton1, toggleButton2;

private Button buttonSubmit;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

addListenerOnButtonClick();

public void addListenerOnButtonClick(){

//Getting the ToggleButton and Button instance from the layout xml file

toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);

toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);

buttonSubmit=(Button)findViewById(R.id.button);

//Performing action on button click

buttonSubmit.setOnClickListener(new View.OnClickListener(){

49
@Override

public void onClick(View view) {

StringBuilder result = new StringBuilder();

result.append("ToggleButton1 : ").append(toggleButton1.getText());

result.append("\nToggleButton2 : ").append(toggleButton2.getText());

//Displaying the message in toast

Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG
).show();

});

50
Output:

51
Android CheckBox Example
Android CheckBox is a type of two state button either checked or unchecked.

There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the
user, activate/deactivate the specific action etc.

Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox class

The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

52
Methods of CheckBox class

There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:

Method Description
public boolean isChecked() Returns true if it is checked otherwise false.
public void setChecked(boolean status) Changes the state of the CheckBox.

Android CheckBox Example

activity_main.xml

Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will
look like this:

File: activity_main.xml

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

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="example.javatpoint.com.checkbox.MainActivity">

<CheckBox

android:id="@+id/checkBox"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

53
android:layout_marginLeft="144dp"

android:layout_marginTop="68dp"

android:text="Pizza"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

<CheckBox

android:id="@+id/checkBox2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="144dp"

android:layout_marginTop="28dp"

android:text="Coffee"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/checkBox" />

<CheckBox

android:id="@+id/checkBox3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="144dp"

android:layout_marginTop="28dp"

android:text="Burger"

54
app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/checkBox2" />

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="144dp"

android:layout_marginTop="184dp"

android:text="Order"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/checkBox3" />

</android.support.constraint.ConstraintLayout>

Activity class

Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java

package example.javatpoint.com.checkbox;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

55
import android.widget.CheckBox;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

CheckBox pizza,coffe,burger;

Button buttonOrder;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

addListenerOnButtonClick();

public void addListenerOnButtonClick(){

//Getting instance of CheckBoxes and Button from the activty_main.xml file

pizza=(CheckBox)findViewById(R.id.checkBox);

coffe=(CheckBox)findViewById(R.id.checkBox2);

burger=(CheckBox)findViewById(R.id.checkBox3);

buttonOrder=(Button)findViewById(R.id.button);

//Applying the Listener on the Button click

buttonOrder.setOnClickListener(new View.OnClickListener(){

@Override

56
public void onClick(View view) {

int totalamount=0;

StringBuilder result=new StringBuilder();

result.append("Selected Items:");

if(pizza.isChecked()){

result.append("\nPizza 100Rs");

totalamount+=100;

if(coffe.isChecked()){

result.append("\nCoffe 50Rs");

totalamount+=50;

if(burger.isChecked()){

result.append("\nBurger 120Rs");

totalamount+=120;

result.append("\nTotal: "+totalamount+"Rs");

//Displaying the message on the toast

Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG


).show();

});

}
57
}

Output:

58
1.Android program for addition of two numbers.
59
Ans:- Below are the steps for Creating a Simple Android Application to Add Two Numbers

 STEP-1: First of all go to the xml file

STEP-2: Now go to the text and write the code for adding 3 textview,2 textedit and Button and Assign
ID to each component. Assign margin top, left, right for the location.

STEP-3: Now, open up the activity java file.

 STEP-4: Declare few variables and the values entered in the Text Views can be read by using
an id which we have set in the XML code above.
 STEP-5: Add the click listener to the Add button.
 STEP-6: When the Add button has been clicked, add the values and store it into the sum
variable.

 STEP-7: To show the output in the result text view, set the sum in the textview.

activity_main.xml
<!--The activity_main.xml is a layout file
an XML-based layout is a file that defines
the different widgets to be used in the UI
and the relations between those widgets
and their containers. -->

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">

<!-- Text view for result view-->


<TextView
android:id="@+id/textView_answer"
android:layout_width="100dp"
android:layout_height="25dp"
android:layout_marginLeft="130dp"
android:layout_marginTop="300dp"
android:text="0"
android:textSize="20dp"
android:textStyle="bold" />

<!--take the input first number-->


<EditText
android:id="@+id/editText_first_no"
android:layout_width="150dp"
android:layout_height="40dp"
60
android:layout_marginLeft="200dp"
android:layout_marginTop="40dp"
android:inputType="number" />
<!-- for messege input first number-->
<TextView
android:id="@+id/textView_first_no"
android:layout_width="150dp"
android:layout_height="25dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="50dp"
android:text="First number"
android:textSize="20dp" />

<!--view messege -->


<TextView
android:id="@+id/textView_second_no"
android:layout_width="150dp"
android:layout_height="25dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="100dp"
android:text="Second number"
android:textSize="20dp" />

<!-- take input for second number -->

<EditText
android:id="@+id/editText_second_no"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="200dp"
android:layout_marginTop="90dp"
android:inputType="number"
tools:ignore="MissingConstraints" />

<!-- button for run add logic and view result -->

<Button
android:id="@+id/add_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="200dp"
android:text="ADD" />

</RelativeLayout>

MainActivity.java
// Each new activity has its own layout and Java files,
// here we build the logic for adding two number

package org.geeksforgeeks.addtwonumbers;

61
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

// define the global variable

// variable number1, number2 for input input number


// Add_button, result textView

EditText number1;
EditText number2;
Button Add_button;
TextView result;
int ans=0;

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

// by ID we can use each component which id is assign in xml file


number1=(EditText) findViewById(R.id.editText_first_no);
number2=(EditText) findViewById(R.id.editText_second_no);
Add_button=(Button) findViewById(R.id.add_button);
result = (TextView) findViewById(R.id.textView_answer);

// Add_button add clicklistener


Add_button.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

// num1 or num2 double type


// get data which is in edittext, convert it to string
// using parse Double convert it to Double type
double num1 =
Double.parseDouble(number1.getText().toString());
double num2 =
Double.parseDouble(number2.getText().toString());
// add both number and store it to sum
double sum = num1 + num2;
// set it ot result textview
result.setText(Double.toString(sum));
}
});
}
}

62
Ans(2):-

How to Add Two No in Android

In my last example we have discussed about the textview and button. Text view to display any
text. In this example we are going to create an app to add two numbers.

Create an android project and use following Text Fields control to take input from the user.

I have taken two textview to display message and one textview to display output. Two plan text
field i.e EditText to take input and one button.

Design Code

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter First Number:-"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textView" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Second Number"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_toRightOf="@+id/editText"
android:layout_toEndOf="@+id/editText" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sum of Two No"
android:id="@+id/button"
android:layout_below="@+id/editText2"
63
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_result"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

Now add a click event to button. Suppose I have created sum method in java file and map this event to
click

public void sum(View v)


{

//get the edit text


EditText t1=(EditText)findViewById(R.id.editText);
EditText t2=(EditText)findViewById(R.id.editText2);

//convert value into int


int x=Integer.parseInt(t1.getText().toString());
int y=Integer.parseInt(t2.getText().toString());

//sum these two numbers


int z=x+y;

//display this text to TextView


TextView tv_data=(TextView)findViewById(R.id.tv_result);
tv_data.setText("The sum is "+z);

Now execute the code and you will get following output:-

Ans(3):- Android Studio: Sum two numbers

If you want to make a program for the sum two numbers in android. The code will be following.

In this app we need

 2 EditText controls to take input of 2 numbers from the user,


 1 Button for getting result after putting the numbers in the EditText controls,
 2 TextView, 1 for setup the heading of the program and 2nd for showing the result.

we will also use of Tost for showing the result.

This android app will cover working of,

64
EditText

TextView

Button

Toast

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="com.techmesolution.anand.helloworld.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sum Numbers"
android:id="@+id/textView" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_marginStart="29dp"
android:layout_marginTop="40dp"
android:id="@+id/num1"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:hint="Enter First Number" />

<Button
android:text="Show Sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="47dp"
65
android:id="@+id/sum"
android:layout_below="@+id/num1"
android:layout_alignStart="@+id/num1" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/num2"
android:hint="Enter Second Number"
android:layout_below="@+id/num1"
android:layout_alignStart="@+id/num1" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showsum"
android:text="Answer"
android:layout_below="@+id/sum"
android:layout_alignStart="@+id/sum"
android:layout_marginTop="19dp" />

</RelativeLayout>

MainActivity.java
package com.techmesolution.anand.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private EditText num1, num2;
private Button sum;
private TextView answer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
66
addListenerOnButton();
}
public void addListenerOnButton(){
num1=(EditText) findViewById(R.id.num1);
num2=(EditText) findViewById(R.id.num2);
sum=(Button) findViewById(R.id.sum);
answer=(TextView) findViewById(R.id.showsum);

sum.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String value1=num1.getText().toString();
String value2=num2.getText().toString();
int a = Integer.parseInt(value1);
int b = Integer.parseInt(value2);
int sum = a+b;
answer.setText(Integer.toString(sum));
Toast.makeText(getApplicationContext(), String.valueOf(sum),
Toast.LENGTH_LONG).show();
}
});
}
}

Ans(another):-

Basic Android Application to Calculate the Sum of Two Numbers

In order to develop an Android App for adding two numbers first, thing we have to do is take
two inputs numbers from the user and by clicking SUM buttons which will add these two
numbers.

Please follow the steps below for creating an Android app to add two numbers:

Step 1) First, go to the text field here and select the number fields for adding two numbers.

Step 2) You can double-click the text box and add the text to this text field but right now text
field is not required because we are not going to display any text on these text boxes but you
the id is important. Id is the unique id which differentiates one phone from another. For
example, this Edit Text id 1 is the id of the first number text and Edit Text id 2 is the id of
the second added text.

Step 3) Now to show this number text or edit we can provide the hint to this text box so for that
you just select this edit text and go to the property called a hint. So there's a property called
hint and here we can provide the hint to the user that what he’s expected to enter here. The

67
hints we assign will appear on our text boxes but it will not appear as a text, it will appear as
a hint.Whatever text you write here will be provided as a hint.

Step 4) Now to add these numbers and to display the message, we can display message by these
plain text views or any other text views from here. We can adjust the length of the text view.
For now, let’s take a large text view.

Step 5) We are going to add one more button to our activity so that whenever this button is
clicked, we should be able to see the results. Therefore in the widgets, just drag and drop the
button.

Step 6) Now our design is complete. We have two text boxes. We have a result text box or
TextEdit or TextView and we have our button.We can also see them in the component tree.

Step 7) Now everything is done, so we will go to our java folder and in the java folder we are
going to go inside the MainActivity.

Step 8 ) In Activity.Java please create a class in order to add the import.android.view.View in


your main class or main activity.java.

public void onButtonClick(View v) {


}
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
Step 9) Now inside the function we have to create a method to add the two integers for that first
we have to insert Edit text and declare our integer variable, for example, num 1 and we will
assign whatever user will enter in this first text box and we will convert this text to the number
and then we are going to use this number to add the values. So this will give us the sum of these
two numbers and then we can display this sum to our text view. So we will take t1 from which
we want to send our text and then dot set text and then we set the text so this is the integer and
then we need to convert this integer to text. So we will write Integer.tostring(sum).

public class MainActivity extends


{
public void onButtonClick(View V)
{
EditText e1=(EditText) findViewByID(R.id.editText);
EditText e2=(EditText) findViewByID(R.id.editText2);
TextView t1=(TextView) findViewByID(R.id.textView);
int num1 =Integer.parseInt(e1.getText().toString()(;
int num2 =Integer.parseInt(e2.getText().toString());
int sum = num1+num2;
68
t1.setText(Integer.toStringly(sum));
}}

Step 10) Now how can we tell this button that we want to call this method when we press this
button. So what we can do is just select the button and in the Properties, we have to find
property called onClick and once you are on click property here, you can just click the combo
box and we will be able to see onButtonclick method automatically appearing there. So now
when we go into the design view, you will see the onButtonclick method.

Step 11) Now whenever we run the program, we will be the result in our emulator. Now in order
to check the application please enter the Number1 and Number2 and click sum, see the result.
Step 12) Now In a similar way, you can use this activity to calculate the subtraction, division or
multiplication of these two numbers. So you can add some more methods and some more buttons
and you can whatever you enter here, you can click subtraction button, or addition button or
multiplication button or division button. That’ll give you the same result. So this application you
can simply extend it to arithmetic operations, different arithmetic operations with the numbers.

Another Ans:-

In this tutorial, we are creating an application to add two numbers(Addition). This tutorial helps
beginners to create a calculator application. By understanding, this tutorial will help you to create
other methods like subtract, multiplication, division.

In our tutorial, we simply created two EditTexts one is used to get 1 number from the user and
another is used to get another number from the user. After that, we added a button when a user
clicks the button, an addition of two EditTexts numbers will show as Toast message.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number one"
android:inputType="numberDecimal" />

<EditText
android:id="@+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number two"

69
android:inputType="numberDecimal" />

<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add" />

</LinearLayout>
MainActivity.java
package com.techyour.test;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

final EditText et1 = findViewById(R.id.et1);


final EditText et2 = findViewById(R.id.et2);
Button btnAdd = findViewById(R.id.btnAdd);

btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int first =
Integer.valueOf(et1.getText().toString().trim());//converting string to int
int second = Integer.valueOf(et2.getText().toString().trim());
int sum = first + second;

Toast.makeText(MainActivity.this, String.valueOf(sum),
Toast.LENGTH_SHORT).show();

et1.getText().clear();
et2.getText().clear();
}
});
}
}

Code Explanation:
 We added android:inputType=”numberDecimal” attribute to two EditTexts which is used to get
only decimal numbers from the user and decimal number keyboard layout will be shown.
 Integer.valueOf(et1.getText().toString().trim()); means get the EditText and removes the empty
spaces and finally converts the String to Integer.

70
 et1.getText().clear(); this will clears the EditText text.

 In our code, we used java string trim() method which eliminates leading and trailing spaces and
return omitted string.

Factorial program in android


Ans:-

package com.droidacid.apticalc.aptitudes;

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

import com.droidacid.apticalc.R;

public class AptiFactorial extends Activity implements


android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;

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

private void initialize() {


number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P")
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}

private long calcFactorial() {

long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}

return factorial;
71
}

@Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " +
calcFactorial());
}

Simple Android Application that makes use


of Database
Procedure:

Creating a New project:


 Open Android Studio and then click on File -> New -> New project.
 Then type the Application name as “ex.no.5″ and click Next.

 Then select the Minimum SDK as shown below and click Next.

 Then select the Empty Activity and click Next.

 Finally click Finish.

 It will take some time to build and load the project.


 After completion it will look as given below.

Designing layout for the Android Application:


 Click on app -> res -> layout -> activity_main.xml.
 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.

Code for Activity_main.xml:

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


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="20dp"
android:text="Student Details"
android:textSize="30sp" />

<TextView

72
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textSize="20sp" />

<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />

<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textSize="20sp" />

<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />

<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
73
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />

<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />

<Button
android:id="@+id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />

<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />

<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp" />

</AbsoluteLayout>

Now click on Design and your application will look as given below.

So now the designing part is completed.

Java Coding for the Android Application:

Click on app -> java -> com.example.exno5 -> MainActivity.

Then delete the code which is there and type the code as given below.

74
Code for MainActivity.java:

package com.example.exno5;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener


{
EditText Rollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);

Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);

// Creating database and table


db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name
VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
// Inserting a record to the Student table
if(view==Insert)
{
// Checking for empty fields
if(Rollno.getText().toString().trim().length()==0||
Name.getText().toString().trim().length()==0||
75
Marks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student VALUES('"+Rollno.getText()
+"','"+Name.getText()+
"','"+Marks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
// Deleting a record from the Student table
if(view==Delete)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE
rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
// Updating a record in the Student table
if(view==Update)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst()) {
db.execSQL("UPDATE student SET name='" + Name.getText() +
"',marks='" + Marks.getText() +
"' WHERE rollno='"+Rollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else {
showMessage("Error", "Invalid Rollno");
}
clearText();
}

76
// Display a record from the Student table
if(view==View)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
// Displaying all the records
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}

77
}
 So now the Coding part is also completed.
 Now run the application to see the output.

78
79

You might also like