Android Lab Manual
Android Lab Manual
Android Lab Manual
Branch : CI
Section :1
AITR, Indore.
Certificate
Signature of Faculty
CSIT Mission
1. To strengthen industry collaboration for maximizing career opportunities ,
professional and entrepreneurship skills .
2. To improve employment marketability, positive attitude , communication skills
and learning agility.
3. To Facilitate value-based research and innovation for broadening knowledge,
skills and intellectual abilities
3. Study of UI in Android
Objective: Student should get the knowledge of android operating system background.
Android Architecture
Android operating system is a stack of software components which is roughly divided into five
sections and four main layers as shown below in the architecture diagram.
Linux kernel At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches.
This provides basic system functionality like process management, memory management, device
management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is
really good at such as networking and vast array of device drivers, which take the pain out of
interfacing to peripheral hardware.
Libraries On top of Linux kernel there is a set of libraries including open -source Web browser
engine WebKit, well known library libc, SQLite database which is a useful repository for storage and
sharing of application data, libraries to play and record audio and video, SSL libraries responsible for
Internet security etc.
Android Runtime This is the third section of the architecture and available on the second layer
from the bottom. This section provides a key component called Dalvik Virtual Machine which is a
kind of Java Virtual Machine specially designed and optimized for Android.
The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.
Application Framework The Application Framework layer provides many higher-level services to
applications in the form of Java classes. Application developers are allowed to make use of these
services in their applications.
Applications You will find all the Android application at the top layer. You will write your
application to be installed on this layer only. Examples of such applications are Contacts Books,
Browser, Games etc.
Android UI An Android application user interface is everything that the user can see and interact
with. You have learned about the various layouts that you can use to position your views in an
activity. This chapter will give you detail on various views.
A View is an object that draws something on the screen that the user can interact with and a
ViewGroupis an object that holds other View (and ViewGroup) objects in order to define the layout
of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML.
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user
interface for your app.
UI Control & Description
TextView This control is used to display text to the user.
RadioButton The RadioButton has two states: either checked or unchecked. RadioGroup
TimePicker The TimePicker view enables users to select a time of the day, in either 24-hour
mode or AM/PM mode.
DatePicker The DatePicker view enables users to select a date of the day.
Create UI Controls
As explained in previous chapter, a view object may have a unique ID assigned to it which will
identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is:
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file and
assign it a unique ID
Then finally create an instance of the Control object and capture it from the layout, use the
following:
Events are a useful way to collect data about a user's interaction with interactive components of your
app, like button presses or screen touch etc. The Android framework maintains an event queue into
which events are placed as they occur and then each event is removed from the queue on a first-in,
first-out (FIFO) basis. You can capture these events in your program and take appropriate action as
per requirements.
• Event Listeners: The View class is mainly involved in building up a Android GUI, same View
class provides a number of Event Listeners. The Event Listener is the object that receives
notification when an event happens.
• Event Listeners Registration: Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the Event Listener fires the
event.
• Event Handlers: When an event happens and we have registered and event listener fo the event,
the event listener calls the Event Handlers, which is the method that actually handles the event.
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc.
Android Studio is fantastic, but it can be difficult to set up properly. Follow these steps and you'll
be good to go in no time.
Android Studio is one of the best programs for Android app development. It offers a plethora of
features and integrated tools for creating professional Android apps.
The program includes a feature-rich Android emulator, testing tools, and a consistent development
environment. In addition, it also features an intelligent code editor that provides you with advanced
code suggestions.
Due to many configuration steps, Android Studio may be challenging to set up if you're a novice
developer. Here, we show how to install Android Studio on Windows and create a sample
application.
Before installing Android Studio, you first need to install the Java JDK and set up the Java
environment to start working on it.
The Java Development Kit (JDK) is a required development package for creating Java-based
applications. Additionally, it also includes tools for developers for testing Java-coded applications.
Follow these steps to get the latest version of Java JDK for Windows and set it up:
Here are the steps you've to perform for setting up the Java environment:
1. Open Windows search and type "Edit environment variables."
2. Hit the Enter key to open the Environment Variables window.
3. Now, under the System variables section, click Path > Edit > New
4. Copy the path of the folder where the JDK binaries are installed. For example, in our case,
the path is C:\Program Files\Java\jdk-18.0.1.1\bin
5. Switch to the Environment variables window and paste the path you've copied and save
the changes.
6. Next, under the User Variables section, click New.
7. Add PATH_HOME in the variable name box and C:\Program Files\Java\jdk-18.0.1.1 in
the variable value box.
8. Finally, save the changes by clicking OK.
Follow these steps to download and install Android Studio for Windows:
1. Visit the Android Developers website and click on Download Android Studio.
2. Now, open the downloaded file to install Android Studio.
3. Click Next to continue installing Android Studio.
4. Further, click Install and wait while Android Studio is being installed on your PC.
5. Once done, click Finish to close the installer and start Android Studio.
6. Android Studio will now ask you to import settings. Click OK to continue to set up
Android Studio.
You should use SSD storage when working with Android Studio to get better performance and
faster processing.
If the installer crashes or closes with a random error code, the chances are that your PC doesn't
meet the minimum system requirements. For this, you must check the below-mentioned
requirements once.
While you've installed Android Studio on your Windows PC, to create a new project you'll have
to configure the Setup Wizard. The Setup Wizard will help you create a development
environment for your future projects.
Follow these steps to set up Android Studio:
1. In the Setup Wizard window, select the Standard option to apply the recommended
settings and click Next.
2. Next, select a theme you want and click Next again to verify the settings you've
configured.
3. On the following screen, select Accept and click Finish to apply the changes.
4. Wait till the Setup Wizard downloads some required files. It may take somewhere around
15 to 30 minutes, depending on your network speed.
5. Once the download is completed, click Finish to complete the setup process.
If it gets stuck while downloading, it's because of either high CPU usage or interruption in
downloading. This is why you must close all the programs that may consume the internet or are
still running in the background.
The first test project takes around 10-15 minutes to load all the files and sync the project using
Gradle (a build automation tool). Once it is done, you can interact with your app's project
structure and view different activities in Android Studio.
After making the changes to your project, you have many different options to run your test
app:
Device Manager: You can create a new emulator from the device manager and run your
app on it. However, the emulator consumes a large number of resources, so we don't
recommend using this option if you're using a low-end PC.
Pair Devices Using Wi-Fi: You can also run the test app on your Android smartphone.
The only condition here is that your smartphone and your PC should be connected to the
same Wi-Fi network.
ADB Connection: Lastly, you can use a USB cable and turn on USB Debugging on your
phone to run your app via an ADB connection.
Objective: Student should be able to design their own UI for android application using XML.
The first step is to create a simple Android Application using Eclipse IDE. Follow the option
File → New → Project and finally select →Android New Application wizard from the wizard list.
Now name your application as HelloWorld using the wizard window as follows:
Next, follow the instructions provided and keep all other entries as default till the final step.
Once your project is created successfully, you will have following project screen:
Before you run your app, you should be aware of a few directories and files in the Android
project:
src
This contains the .java source files for your project. By default, it includes an MainActivity.java
source file having an activity class that runs when your app is launched using the app icon.
gen
This contains the .R file, a compiler-generated file that references all the resources found in
your project. You should not modify this file.
bin
This folder contains the Android package files .apk built by the ADT during the build process
and everything else needed to run an Android application.
res/drawable-hdpi
This is a directory for drawable objects that are designed for high-density screens.
res/layout
This is a directory for files that define your app's user interface.
res/values
This is a directory for other various XML files that contain a collection of resources, such as
strings and colors definitions.
AndroidManifest.xml
This is the manifest file which describes the fundamental characteristics of the app and defines
each of its components.
The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs
your application. Following is the default code generated by the application wizard for
Hello World! Application:
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{ getMenuInflater().inflate(R.menu.activity_main, menu); return true;
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
TheonCreate() method is one of many methods that are fired when an activity is loaded.
Whatever component you develop as a part of your application, you must declare all its
components in a manifest file called AndroidManifest.xml which ressides
at the root of the application project directory. This file works as an interface between Android
OS and your application, so if you do not declare your component in this file, then it will not be
considered by the OS. For example, a default manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is
namedandroid.intent.category.LAUNCHER to indicate that the application can be launched from
the device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to
theapp_name string defined in the strings.xml fi le, which is "HelloWorld". Similar way, other
strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different
Android application components:
The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file:
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string> <string
name="menu_settings">Settings</string> <string
name="title_activity_main">MainActivity</string>
</resources>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
The TextView is an Android control used to build the GUI and it have various attribuites like
android:layout_width,android:layout_height etc which are being used to set its width and height
etc. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the strings.xml fi le, which is "Hello
World!".
Let's try to run our Hello World! application we just created. I assume you had created your
AVD while doing environment setup. To run the app from Eclipse, open one of your project's
activity files and click Run icon from the toolbar. Eclipse installs the app on your AVD and
starts it and if everything is fine with your setup and application, it will display following
Emulator window:
Objective: Student should get the knowledge of developing an application android activity
lifecycle.
An activity is the single screen in android. It is like window or frame of Java. By the help of
activity, you can place all your UI components or widgets in a single screen. The 7 lifecycle
method of Activity describes how activity will behave at different states.
onResume called when activity will start interacting with the user.
File: MainActivity.java
1. package example.javatpoint.com.activitylifecycle;
2. import android.app.Activity;
3. import android.os.Bundle;
4. import android.util.Log;
5. public class MainActivity extends Activity {
6. @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked"); }
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked"); }
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked"); }
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked"); }
@Override
Output:
You will not see any output on the emulator or device. You need to open logcat.
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Now see on the logcat: onRestart, onStart and onResume methods are invoked.
Now click on the back button. Now you will see onPause methods is invoked.
Now click on the back button. Now you will see onPause methods is invoked.
After a while, you will see onStop and onDestroy methods are invoked.
*** The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.
Practical 5
Modify the default content of res/layout/activity_main.xml file to include a few buttons in linear
layout.
No need to change string Constants.Android studio takes care of default strings
Run the application to launch the Android emulator and verify the result of the changes done in
the application.
Example 1
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button android:id="@+id/btnStartService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="Start"/>
<Button android:id="@+id/btnPauseService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="Pause"/>
<Button android:id="@+id/btnStopService"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:text="Stop"/>
</LinearLayout>
<TextView
android:id="@+id/txt_instruction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Relative view Demo"
android:gravity="center"/>
<TextView
android:id="@+id/txt_1"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txt_instruction"
android:text="Enter User Name"/>
<EditText
android:id="@+id/txt_price"
<TextView
android:id="@+id/txt_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_below="@+id/txt_1"
android:text="Enter Password"/>
<EditText
android:id="@+id/txt_cash_down_payment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="-10dp"
android:layout_below="@id/txt_price"
android:layout_alignParentRight="true"
android:text="Nisha123" />
<TextView
android:id="@+id/txt_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_below="@+id/txt_2"
android:text="Enter Semester"/>
<RadioGroup
android:id="@+id/select_year"
android:orientation="vertical"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txt_cash_down_payment">
<RadioButton
android:id="@+id/year2"
android:text="I sem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/year3"
android:text="II sem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/year4"
</RadioGroup>
<TextView
android:id="@+id/txt_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/select_year"
android:layout_centerInParent="true"
android:text="Press below button to confirm submission"/>
<Button
android:id="@+id/button_loanReport"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/txt_3"
android:layout_centerInParent="true"
android:text="Submit"
/>
</RelativeLayout>
Objective: Student should know what is intent in android and whatare the types of it.
Outcome: Student will develop a good application using the intents and its properties efficiently
An intent is a messaging object used to request any action from another app component. Intents
facilitate communication between different components in several ways. The intent is used to
launch an activity, start the services, broadcast receivers, display a web page, dial a phone call,
send messages from one activity to another activity, and so on.
Type Of Intent
Explicit Intent: Explicit intents are communicated between two activities inside the same
application. We can use explicit intents when we need to move from one activity to another
activity.
Example:- when a user wants to start a service to download a file or when a new activity gets
started in response to a user action.
//Explicit Intent
Intent send = new Intent(FirstActivtiy.this,
SecondActivity.class);
//Starts TargetActivity
startActivity(send);
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.application.myapplication.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
activity_2.xml
MainActivity.Java
} package com.example.application.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@Override
Activity2.Java
package com.example.application.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Implicit Intent: Implicit intent is communicated between two activities of an application. One
thing to note here is we should not name a specific component. In place of that we can declare a
general action to perform which allows a component from another app to handle it.
Example:- To show the user a location on a map, we can use an implicit intent.
//Implicit intent
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(Contract.Contacts.CONTENT_URL);
startActivity(intent);
activity_main.xml
MainActivity.java
package com.example.implicitintent; //package name
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
button = findViewById(R.id.button);
editText = findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() { //add the listener on button
@Override
public void onClick(View view) {
//string type variable
String url = editText.getText()
.toString(); //for storing edtitextvalue
Outcome: Student will demonstrate the database development using SQLite for basic queries.
What is SQLite?
SQLite is an Open Source database. SQLite supports standard relational database features like
SQL syntax, transactions and prepared statements. The database requires limited memory at
runtime (approx. 250 KByte) which makes it a good candidate from being embedded into other
runtimes.
SQLite supports the data types TEXT (similar to String in Java), INTEGER (similar to long in
Java) and REAL (similar to double in Java).
All other types must be converted into one of these fields before getting saved in the database.
SQLite itself does not validate if the types written to the columns are actually of the defined type,
e.g. you can write an integer into a string column and vice versa.
SQLite in Android
SQLite is embedded into every Android device. Using an SQLite database in Android does not
require a setup procedure or administration of the database.
You only have to define the SQL statements for creating and updating the database. Afterwards
the database is automatically managed for you by the Android platform.
Access to a SQLite database involves accessing the file system. This can be slow.
I f your application creates a database, this database is by default saved in the directory
DATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path
which theEnvironment.getDataDirectory() method returns. APP_NAME is your application
name. FILENAME is the name you specify in your application code for the database.
SQLite architecture
Packages
To create and upgrade a database in your Android application you create a subclass of the
SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of
SQLiteOpenHelper, specifying the database name and the current database version.
In this class you need to override the following methods to create and update your database.
onCreate() - is called by the framework, if the database is accessed but not yet created.
onUpgrade() - called, if the database version is increased in your application code. This method
allows you to update an existing database schema or to drop the existing database and recreate it
via the onCreate() method.
Both methods receive an SQLiteDatabase object as parameter which is the Java representation of
the database.
The database tables should use the identifier _id for the primary key of the table.
Note:
It is good practice to create a separate class per table. This class defines static onCreate()
andonUpgrade() methods. These methods are called in the corresponding methods of
SQLiteOpenHelper. This way your implementation of SQLiteOpenHelper stays readable, even if
you have several tables.
SQLiteDatabase
SQLiteDatabase is the base class for working with a SQLite database in Android and provides
methods to open, query, update and close the database.
More specifically SQLiteDatabase provides the insert(), update() and delete() methods.
In addition it provides the execSQL() method, which allows to execute an SQL statement
directly.
The object ContentValues allows to define key/values. The key represents the table column
identifier and the value represents the content for the table record in this column. ContentValues
can be used for inserts and updates of database entries.
Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder
class .
rawQuery() Example
query() Example
The following gives an example of a query() call.
Parameter Comment
The "whereClause" is specified without the word "where", for example a "where" statement
might look like: "_id=19 and summary=?".
If you specify placeholder values in the where clause via ?, you pass them as the selectionArgs
parameter to the query.
Cursor
A query returns a Cursor object. A Cursor represents the result of a query and basically points
to one row of the query result. This way Android can buffer the query results efficiently; as it
does not have to load all data into memory.
To get the number of elements of the resulting query use the getCount() method.
To move between individual data rows, you can use the moveToFirst() and moveToNext()
methods. The isAfterLast()method allows to check if the end of the query result has been
reached.
Cursor also provides the getColumnIndexOrThrow(String) method which allows to get the
column index for a column name of the table.
ListViews are Views which allow to display a list of elements. ListActivities are specialized
activities which make the usage of ListViews easier. To work with databases and ListViews you
can use the SimpleCursorAdapter. The SimpleCursorAdapter allows to set a layout for each row
of the ListViews.
You also define an array which contains the column names and another array which contains
the IDs of Views which should be filled with the data.
The SimpleCursorAdapter class will map the columns to the Views based on the Cursor passed
to it. To obtain the Cursor you should use the Loader class.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Garv Bhatt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.577" />
</androidx.constraintlayout.widget.ConstraintLayout>
Output:
<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"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Garv Bhatt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.577" />
<!-- on below line we are creating edit text for number 1 -->
<EditText
android:id="@+id/idEdtNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:textColor="@android:color/black" />
<!-- on below line we are creating edit text for number 2 -->
<EditText
android:id="@+id/idEdtNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:inputType="number"
android:textColor="@android:color/black" />
<!-- on below line we are creating button for adding two numbers-->
<Button
android:id="@+id/idBtnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:padding="4dp"
android:text="Add"
android:textAllCaps="false"
app:background="@color/black"
app:backgroundTint="@color/black" />
<!-- on below line we are creating text view for displaying the sum -->
<TextView
android:id="@+id/idTVSum"
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_margin="20dp"
android:padding="4dp"
android:text="Sum"
android:textAlignment="center"
android:textColor="@android:color/black"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
MainActivity.java
package com.example.Garv_layout;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
// on below line creating a variables for edit text, button and text
views.
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberOneEdt = findViewById(R.id.idEdtNumber1);
numberTwoEdt = findViewById(R.id.idEdtNumber2);
addBtn = findViewById(R.id.idBtnAdd);
sumTV = findViewById(R.id.idTVSum);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
if (!numberOneEdt.getText().toString().isEmpty() && !
numberTwoEdt.getText().toString().isEmpty()) {
// on below line getting num1 and num2 from our edit text
int num1 =
Integer.parseInt(numberOneEdt.getText().toString());
int num2 =
Integer.parseInt(numberTwoEdt.getText().toString());
sumTV.setText(String.valueOf(sum));
});
Output:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="abhiandroid.com.calculater.MainActivity"
android:orientation="vertical"
android:gravity="top"
android:textAlignment="center"
android:background="@android:color/holo_blue_bright"
android:weightSum="1">
<TextView
android:text="@string/enter_two_numbers"
android:layout_width="match_parent"
android:id="@+id/textView"
android:layout_height="30dp"
android:gravity="center_horizontal"
android:textColorLink="?android:attr/editTextColor"
tools:textStyle="bold|italic"
android:visibility="visible"
android:textSize="24sp"
android:layout_weight="0.07" />
android:textStyle="bold|italic"
android:fontFamily="serif"
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:textSize="18sp"
android:gravity="center_horizontal"
android:layout_marginBottom="5dp"
android:visibility="visible" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editOp2"
android:textSize="18sp"
android:gravity="center_horizontal"
android:elevation="1dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="+"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:id="@+id/btnadd"
android:layout_weight="0.03" />
<Button
android:layout_width="78dp"
android:layout_height="wrap_content"
android:id="@+id/btnsub"
android:layout_weight="0.03" />
<Button
android:text="*"
android:layout_width="78dp"
android:layout_height="wrap_content"
android:id="@+id/btnmul"
android:layout_weight="0.03"/>
<Button
android:text="/"
android:layout_height="wrap_content"
android:id="@+id/btndiv"
android:layout_width="78dp"
android:layout_weight="0.03" />
<Button
android:text="Clear"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="@+id/btnclr"
android:layout_weight="0.03" />
</LinearLayout>
<TextView
android:layout_width="332dp"
android:id="@+id/textView1"
android:layout_marginTop="10dp"
android:layout_height="50dp"
android:gravity="center_horizontal"
android:textColorLink="?android:attr/editTextColor"
tools:textStyle="bold|italic"
android:textStyle="bold|italic"
android:fontFamily="serif"
android:visibility="visible"
android:textSize="30sp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/result"
android:textSize="18sp"
android:text="0.00"
android:gravity="center_horizontal" />
</LinearLayout>
Main_Activity.java
package com.example.calculatora1;
import androidx.appcompat.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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Addition
btnadd.setOnClickListener(new View.OnClickListener() {
@Override
double oper1 =
Double.parseDouble(opr1.getText().toString());
double oper2 =
Double.parseDouble(opr2.getText().toString());
txtresult.setText(Double.toString(result));
else{
toast.show();
});
//Subtraction
btnsub.setOnClickListener(new View.OnClickListener() {
@Override
double oper1 =
Double.parseDouble(opr1.getText().toString());
txtresult.setText(Double.toString(result));
else{
toast.show();
});
// Multiplication
btnmul.setOnClickListener(new View.OnClickListener() {
@Override
double oper1 =
Double.parseDouble(opr1.getText().toString());
double oper2 =
Double.parseDouble(opr2.getText().toString());
txtresult.setText(Double.toString(result));
else{
toast.show();
});
// Division
btndiv.setOnClickListener(new View.OnClickListener() {
@Override
double oper1 =
Double.parseDouble(opr1.getText().toString());
double oper2 =
Double.parseDouble(opr2.getText().toString());
txtresult.setText(Double.toString(result));
else{
toast.show();
});
// Reset Feilds
btnclr.setOnClickListener(new View.OnClickListener() {
@Override
opr1.setText("");
opr2.setText("");
txtresult.setText("0.00");
opr1.requestFocus();
});
Output:
Activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
android:stretchColumns="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Garv Bhatt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.528"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.577" />
<TableRow android:padding="5dip">
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:text="@string/userName"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/userName"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:background="#fff"
android:hint="@string/userName"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow>
<TextView
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:text="@string/password"
android:textColor="#fff"
android:textSize="16sp" />
<EditText
android:id="@+id/password"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:background="#fff"
android:hint="@string/password"
android:padding="5dp"
android:textColor="#000" />
</TableRow>
<TableRow android:layout_marginTop="20dp">
Main_Activity.java
package com.example.loginregister;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate a button
Button loginButton = (Button) findViewById(R.id.loginBtn);
// perform click event on the button
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello world..!!!",
Toast.LENGTH_LONG).show(); // display a toast message
}
});
}
strings.xml
<resources>
<string name="app_name">TableLayoutExample</string>