SlideShare a Scribd company logo
1 of 88
PRACTICAL JOURNAL OF ANDROID PROGRAMMING
BE : VI Semester
Department of Computer Science and Information Technology
Name : Palak Jaiswal
Branch : CI
Section : 2
Roll No. : 0827CI201126
Session : Jan-Jun 2023
Department of Computer Science and Information Technology
ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
Department of Computer Science Engineering
Certificate
This is to certify that the experimental work entered in this journal
as per the B.Tech III year syllabus prescribed by the RGPV was
done by Ms. Palak Jaiswal B.Tech-VI semester CI in the Android
Programming Laboratory of this institute during the academic year
2023.
Signature of Faculty
LAB INDEX
1. Introduction to android operating system and study of basic widgets.
2. Study of android lifecycle and demonstration of it.
3. Study of Different Layouts
4. To build Calculator App using Linear Layouts
5. To Build Login App using different Layouts
6. To Build a Stop Watch Application
7. To Build a Business Visiting Card
8. To Study and Build Applications using Intents
9. To Build Quiz App
10.To Build Tic Tac Game
Assignment 1
Aim: Introduction to android
Objective: Student should get the knowledge of android operating system
background.
Outcome: Student will be aware of the android operating system.
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
a 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 Dalvik VM makes use of Linux core features like memory management and
multi-threading, which is intrinsic in the Java language. The Dalvik VM
enables every Android application to run in its own process, with its own
instance of the Dalvik virtual machine.
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. For example, a simple vertical layout with a
text view and a button looks like this:
<?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" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
Android UI Controls
There are number of UI controls provided by Android that allow you to build
the graphical user interface for your app.
S.N. UI Control & Description
TextView
1
This control is used to display text to the user.
EditText
2 EditText is a predefined subclass of TextView that includes rich
editing capabilities.
AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText,
3
except that it shows a list of completion suggestions
automatically while the user is typing.
Button
4 A push-button that can be pressed, or clicked, by the user
to perform an action.
ImageButton
5 AbsoluteLayout enables you to specify the exact location of
its children.
CheckBox
An on/off switch that can be toggled by the user. You
should 6
use checkboxes when presenting users with a group
of selectable options that are not mutually exclusive.
ToggleButton
7
An on/off button with a light indicator.
RadioButton
8
The RadioButton has two states: either checked or unchecked.
RadioGroup
9 A RadioGroup is used to group together one or more
RadioButtons.
ProgressBar
The ProgressBar view provides visual feedback about some
10
ongoing tasks, such as when you are performing a task in the
background.
Spinner
11
A drop-down list that allows users to select one value from a
set. TimePicker
12 The TimePicker view enables users to select a time of the day,
in either 24-hour mode or AM/PM mode.
DatePicker
13
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 as follows:
<?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" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from
the layout, use the following:
TextView myText = (TextView) findViewById(R.id.text_id);
Android Event Handling
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.
There are following three concepts related to Android Event Management:
• 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 happes.
• 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.
Event Listeners & Event Handlers
Event Handler Event Listener & Description
OnClickListener()
onClick()
This is called when the user either clicks or
touches or focuses upon any widget like button,
text, image etc. You will use onClick() event
handler to handle such event.
OnLongClickListener()
This is called when the user either clicks or
onLongClick()
touches or focuses upon any widget like button,
text, image etc. for one or more seconds. You will
use onLongClick() event handler to handle such
event.
OnFocusChangeListener()
onFocusChange()
This is called when the widget looses its focus ie.
user goes away from the view item. You will use
onFocusChange() event handler to handle such
event.
OnFocusChangeListener()
onKey() This is called when the user is focused on the
item and presses or releases a hardware key on
the device. You will use onKey() event handler to
handle such event.
OnTouchListener()
onTouch()
This is called when the user presses the key,
releases the key, or any movement gesture on the
screen. You will use onTouch() event handler to
handle such event.
OnMenuItemClickListener()
onMenuItemClick() This is called when the user selects a menu item.
You will use onMenuItemClick() event handler to
handle such event.
There are many more event listeners available as a part of View class like
OnHoverListener, OnDragListener etc which may be needed for your
application. So I recommend to refer official documentation for Android
application development in case you are going to develop a sophisticated apps.
Exercise:
Key points to study: History, Versions, Architecture, IDE (Eclipse), SDK
of android.
Assignment 2
Aim: Study of UI in Android
Objective: Student should be able to design their own UI for android
application using XML.
Outcome: Student will demonstrate the basic application using UI in android.
Create Android Application
The first step is to create a simple Android Application using Eclipse IDE.
Follow the option
File
→
New
→
Project and finally select
→
Android New Application wizard
from the wizard list. Now name your application as HelloWorld using the
wizard window as follows:
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:
Anatomy of Android Application
Before you run your app, you should be aware of a few directories and files in
the Android project:
S.N. Folder, File & Description
1 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
2
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
3
ADT during the build process and everything else needed to run
an Android application.
res/drawable-hdpi
4 This is a directory for drawable objects that are designed for
high-density screens.
res/layout
5
This is a directory for files that define your app's user interface.
res/values
6 This is a directory for other various XML files that contain a
collection of resources, such as strings and colors definitions.
AndroidManifest.xml
7 This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
Following section will give a brief overview few of the important application files.
The Main Activity File
The main activity code is a Java file MainActivity.java. This is the actual
application file which ultimately gets converted to a Dalvik executable and runs
your application. Following is the default code generated by the
application wizard for Hello World! application:
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,
menu); return true;
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the
res/layout folder. TheonCreate() method is one of many methods that are fi red
when an activity is loaded.
The Manifest File
Whatever component you develop as a part of your application, you must declare
all its components in a manifest file called AndroidManifest.xml which ressides
at the root of the application project directory. This file works as an interface
between Android OS and your application, so if you do not declare your
component in this file, then it will not be considered by the OS. For example, a
default manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main"
> <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Here <application>...</application> tags enclosed the components related to
the application. Attributeandroid:icon will point to the application icon available
under res/drawable-hdpi. The application uses the image named
ic_launcher.png located in the drawable folders
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:
<activity>elements for activities
<service> elements for services
<receiver> elements for broadcast receivers
<provider> elements for content providers
The Strings File
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>
The R File
The gen/com.example.helloworld/R.java file is the glue between the activity
Java files likeMainActivity.java and the resources like strings.xml. It is an
automatically generated file and you should not modify the content of the
R.java file. Following is a sample of R.java file:
/* 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.helloworld;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int padding_large=0x7f040002;
public static final int padding_medium=0x7f040001;
public static final int padding_small=0x7f040000;
}
public static final class drawable {
public static final int ic_action_search=0x7f020000;
public static final int ic_launcher=0x7f020001;
}
public static final class id {
public static final int menu_settings=0x7f080000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f070000;
}
public static final class string {
public static final int app_name=0x7f050000; public
static final int hello_world=0x7f050001; public static
final int menu_settings=0x7f050002; public static
final int title_activity_main=0x7f050003;
}
public static final class style {
public static final int AppTheme=0x7f060000;
}
}
The Layout File
The activity_main.xml is a layout file available in res/layout directory, that is
referenced by your application when building its interface. You will modify this file
very frequently to change the layout of your application. For your "Hello World!"
application, this file will have following content related to default layout:
<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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate
chapter. 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!".
Running the Application
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:
Exercise:
Key points to study: Package explorer (Description about folders e.g. src,
gen,res, etc.), Description about XML file, Layouts.
1. Develop an application Hello world program description about tags
used in XML
File: activity_main.xml
Android studio auto generates code for activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.androi
d.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="first.javatpoint.com.welcome.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
}
File: MainActivity.java
package first.javatpoint.com.welcome;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} }
2. Develop an application using basic controls like button,
textview, edittext etc. e.g. application for calculator.
File: 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="ExtraText">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="83dp"
android:onClick="Add"
android:text="ADD" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="82dp"
android:onClick="Sub"
android:text="SUBTRACT" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="105dp"
android:onClick="Mult"
android:text="MULTIPLY" />
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="79dp"
android:onClick="Div"
android:text="DIVIDE" />
<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="64dp"
android:ems="10"
android:inputType="number"
android:text="Enter Number" />
<EditText
android:id="@+id/editTextNumber3"
android:layout_width="match_parent"
android:layout_height="73dp"
android:ems="10"
android:inputType="number"
android:text="Enter Number" />
<EditText
android:id="@+id/editTextNumber4"
android:layout_width="match_parent"
android:layout_height="76dp"
android:ems="10"
android:inputType="number"
android:text="Answer" />
</LinearLayout>
File: MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myapplication.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
String TAG ="MainActivity";
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
@Override
protected void onCreate( Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i( TAG, "--onCreate--");
}
public void Add(View v){
EditText et1=(EditText)findViewById(R.id.editTextNumber2);
EditText et2=(EditText)findViewById(R.id.editTextNumber3);
EditText et3=(EditText)findViewById(R.id.editTextNumber4);
int n1= Integer.parseInt(et1.getText().toString());
int n2= Integer.parseInt(et2.getText().toString());
int result=n1+n2;
et3.setText("Total Value" + result);
}
public void Sub(View v){
EditText et1=(EditText)findViewById(R.id.editTextNumber2);
EditText et2=(EditText)findViewById(R.id.editTextNumber3);
EditText et3=(EditText)findViewById(R.id.editTextNumber4);
int n1= Integer.parseInt(et1.getText().toString());
int n2= Integer.parseInt(et2.getText().toString());
int result=n1-n2;
et3.setText("Subtract Value" +result);
}
public void Mult(View v){
EditText et1=(EditText)findViewById(R.id.editTextNumber2);
EditText et2=(EditText)findViewById(R.id.editTextNumber3);
EditText et3=(EditText)findViewById(R.id.editTextNumber4);
int n1= Integer.parseInt(et1.getText().toString());
int n2= Integer.parseInt(et2.getText().toString());
int result=n1*n2;
et3.setText("Multiplication Value" +result);
}
public void Div(View v){
EditText et1=(EditText)findViewById(R.id.editTextNumber2);
EditText et2=(EditText)findViewById(R.id.editTextNumber3);
EditText et3=(EditText)findViewById(R.id.editTextNumber4);
int n1= Integer.parseInt(et1.getText().toString());
int n2= Integer.parseInt(et2.getText().toString());
int result=n1/n2;
et3.setText("Division Value" + result);
}
}
Exercise 3
Aim: Study of Activity LifeCycle
Objective: Student should get the knowledge of android activity lifecycle.
Outcome: Student will demonstrate the Activity lifecycle through the
application.
Activity life cycle
States of an activity
An activity can be in different states depending how it is interacting with
the user. These states are described by the following table.
Table 1. Activity state
State Description
Running
Paused
Activity is visible and interacts with the user.
Activity is still visible but partially obscured, instance is
running but might be killed by the system.
Stopped
Killed
Activity is not visible, instance is running but might be killed by
the system.
Activity has been terminated by the system of by a call to its
finish() method.
The live cycle methods
The Android system defines a life-cycle for activities via predefined life-
cycle methods. The most important methods are:
Table 3. Important Activity lifecycle methods
Method Purpose
onCreate()
onResume()
onPause()
Called then the activity is created. Used to initialize the activity, for
example create the user interface.
Called if the activity get visible again and the user starts interacting
with the activity again. Used to initialize fields, register listeners,
bind to services, etc.
Called once another activity gets into the foreground. Always called
before the activity is not visible anymore. Used to release resources or
save application data. For example you unregister listeners, intent
receivers, unbind from services or remove system service listeners.
onStop() Called once the activity is no longer visible. Time or CPU intensive
shut-down operations, such as writing information to a database
should be down in the onStop() method. This method is guaranteed
to be called as of API 11.
The life cycle of an activity with its most important methods is displayed in
the following diagram.
Android has more life cycle methods but not all of these methods are
guaranteed to be called. The onDestroy() method is not guaranteed to be called,
hence you typically do not use it.
Activity instance state
Instance state of an activity which is required to restore the activity to the state in
which the user left it. This is non-persistent application data that needs to be
passed between activities restarts during a configuration change to restore user
selections. The application is responsible for restoring its instance state.
Assume for example the user scrolled through a ListView with thousands of
items and the activity is recreated. Loosing the position in the list is annoying
for the user, hence the position should be restored.
The onSaveInstanceState() can be used to store this instance state as a
Bundle. A Bundle can contain primitive data types, arrays, String and objects
which are of the Parcelable or Serialisable type.
The persisted Bundle data is passed at restart of the activity to the onCreate()
method and onRestoreInstanceState() as parameter.
If you override onSaveInstanceState() and onRestoreInstanceState() you
should call the super implementation of it, because the default views of
Android store their data via a call to View.onSaveInstanceState from the
onSaveInstanceState() method of the activity. For example EditText stores its
content via the default call of this method.
The onRestoreInstanceState() or the onCreate() methods can be used to
recreate the instance scope of an activity if it is restarted.
Exercise:
Key point to study: Description about Activity LifeCycle
Develop an application demonstrating Activity LifeCycle
File: MainActivity.java
@Override
protected void onCreate( Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i( TAG, "--onCreate--");
}
protected void onStart() {
super.onStart();
Log.i( TAG, "--onStart--");
}
@Override
protected void onRestart() {
super.onRestart();
Log.i( TAG, "--onRestart--");
}
@Override
protected void onResume() {
super.onResume();
Log.i( TAG, "--onResume--");
}
@Override
protected void onPause() {
super.onPause();
Log.i( TAG, "--onPause--");
}
@Override
protected void onStop() {
super.onStop();
Log.i( TAG, "--onStop--");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i( TAG, "--onDestroy--");
}
File: activity_main.xml
package com.example.myapplication;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myapplication.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
String TAG ="MainActivity";
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
Assignment 4
Aim: Study of Intents in android
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
Intents and intent filter
What are intents?
Intents are asynchronous messages which allow application components to
request functionality from other Android components. Intents allow you to
interact with components from the same applications as well as with
components contributed by other applications. For example, an activity can
start an external activity for taking a picture.
Intents are objects of the android.content.Intent type. Your code can send them
to the Android system defining the components you are targeting. For example,
via the startActivity() method you can define that the intent should be used to
start an activity. An intent can contain data via a Bundle. This data can be
used by the receiving component. Starting activities. To start an activity, use
the method startActivity(intent). This method is defined on the Context object
which activity extends.
The following code demonstrates how you can start another activity via
an intent.
# Start the activity connect to the
# specified class
Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);
Sub-activities
Activities which are started by other Android activities are called sub-activities.
This wording makes it easier to describe which activity is meant.
Starting services
You can also start services via intents. Use the startService(Intent) method call
for that.
Different types of intents
Android supports explicit and implicit intents. An application can define the
target component directly in the intent (explicit intent) or ask the Android system
to evaluate registered components based on the intent data (implicit intents).
Explicit Intents
Explicit intents explicitly define the component which should be called by the
Android system, by using the Java class as identifier.
The following shows how to create an explicit intent and send it to the
Android system. If the class specified in the intent represents an activity, the
Android system starts it.
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo
"); i.putExtra("Value2", "This value two ActivityTwo");
Explicit intents are typically used within on application as the classes in an
application are controlled by the application developer.
Implicit Intents
Implicit intents specify the action which should be performed and optionally
data which provides content for the action.
For example, the following tells the Android system to view a webpage. All
installed web browsers should be registered to the corresponding intent data
via an intent filter.
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.exercise.com"));
startActivity(i);
If an implicit intent is sent to the Android system, it searches for all components
which are registered for the specific action and the fitting data type.
If only one component is found, Android starts this component directly. If several
components are identified by the Android system, the user will get a selection
dialog and can decide which component should be used for the intent.
Data transfer between activities
Data transfer to the target component: An intent contains certain header data,
e.g., the desired action, the type, etc. Optionally an intent can also contain
additional data based on an instance of the Bundle class which can be
retrieved from the intent via the getExtras() method.
You can also add data directly to the Bundle via the overloaded putExtra()
methods of the Intent objects. Extras are key/value pairs. The key is always of
type String. As value you can use the primitive data types (int, float, ...) plus
objects of type String, Bundle, Parceable and Serializable.
The receiving component can access this information via the getAction() and
getData() methods on the Intent object. ThisIntent object can be retrieved via
the getIntent() method.
The component which receives the intent can use the getIntent().getExtras()
method call to get the extra data. That is demonstrated in the following code
snippet.
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT); if
(value1 != null) {
// do something with the data
}
Example: Using the share intent
Lots of Android applications allow you to share some data with other people,
e.g., the Facebook, G+, Gmail and Twitter application. You can send data to
one of these components. The following code snippet demonstrates the usage
of such an intent within your application.
// this runs, for example, af ter a button click Intent intent = new
Intent(Intent.ACTION_SEND); intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent);
Retrieving result data from a sub-activity
An activity can be closed via the back button on the phone. In this case the
finish() method is performed. If the activity was started with the
startActivity(Intent) method call, the caller requires no result or feedback from
the activity which now is closed.
If you start the activity with the startActivityForResult() method call, you
expect feedback from the sub-activity. Once the sub-activity ends, the
onActivityResult() method on the sub-activity is called and you can perform
actions based on the result.
In the startActivityForResult() method call you can specify a result code to
determine which activity you started. This result code is returned to you. The
started activity can also set a result code which the caller can use to
determine if the activity was canceled or not.
T he sub-activity uses the finish() method to create a new intent and to put
data into it. It also sets a result via the setResult()method call.
The following example code demonstrates how to trigger an intent with the
startActivityForResult() method.
public void onClick(View view) {
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
// set the request code to any code you like,
// you can identif y the callback via this code
startActivityForResult(i, REQUEST_CODE);
}
If you use the startActivityForResult() method, then the started activity is
called a sub-activity.
If the sub-activity is finished, it can send data back to its caller via an Intent.
This is done in the finish() method.
@Override
public void finish() {
// Prepare data intent
Intent data = new Intent();
data.putExtra("returnKey1", "Swinging on a star. ");
data.putExtra("returnKey2", "You could be better then you are. ");
// Activity f inished ok, return the
data setResult(RESULT_OK, data);
super.finish();
}
Once the sub-activity finishes, the onActivityResult() method in the calling
activity is called.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE)
{ if (data.hasExtra("returnKey1")) {
Toast.makeText(this, data.getExtras().getString("returnKey1"),
Toast.LENGTH_SHORT).show();
}
}
}
Defining intent filters
Intent filter
Intents are used to signal to the Android system that a certain event has
occurred. Intents often describe the action which should be performed and
provide data upon which such an action should be done. For example, your
application can start a browser component for a certain URL via an intent.
This is demonstrated by the following example.
String url = "http://www.exercise.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); startActivity(i);
But how does the Android system identify the components which can react to
a certain intent?
A component can register itself via an intent f ilter for a specific action and
specific data. An intent filter specifies the types of intents to which an activity,
service, or broadcast receiver can respond to by declaring the capabilities of a
component.
Android components register intent filters either statically in the
AndroidManifest.xml or in case of a broadcast receiver also dynamically via
code. An intent filter is defined by its category, action and data filters. It can
also contain additional meta-data.
If an intent is sent to the Android system, the Android platform runs a
receiver determination. It uses the data included in the intent. If several
components have registered for the same intent filter, the user can decide
which component should be started.
Defining intent filter
You can register your Android components via intent filters for certain events.
If a component does not define one, it can only be called by explicit intents.
This chapter gives an example for registering a component for an intent. The
key for this registration is that your component registers for the correct
action, mime-type and specifies the correct meta-data.
If you send such an intent to your system, the Android system determines all
registered Android components for this intent. If several components have
registered for this intent, the user can select which one should be used.
Exercise:
Key points to study: Description about Intent. Types of Intents.
Develop an application which demonstrate the efficient use of explicit
and implicit intents
Ans-
There are two types of intents in android
1. Implicit Intent
2. Explicit Intent
Implicit Intent
Using implicit Intent, components can’t be specified. An action to be performed
is declared by implicit intent. Then android operating system will filter out
components that will respond to the action. no component is specified, instead,
an action is performed i.e. a webpage is going to be opened. As you type the
name of your desired webpage and click on the ‘CLICK’ button. Your webpage
is opened.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:text="Search"
android:onClick="search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
File: MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
EditText editText;
Button button;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url=editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
}
}
Explicit Intent
Using explicit intent any other component can be specified. In other words, the
targeted component is specified by explicit intent. So only the specified target
component will be invoked. For Example:
In the above example,
There are two activities (FirstActivity, and SecondActivity). When you click on
the ‘GO TO OTHER ACTIVITY’ button in the first activity, then you move to the
second activity. When you click on the ‘GO TO HOME ACTIVITY’ button in the
second activity, then you move to the first activity. This is getting done through
Explicit Intent.
1. Introduction to android operating system and study of
basic widgets.
A widget is a small gadget or control of your android application placed on the
home screen. Widgets can be very handy as they allow you to put your
favourite applications on your home screen in order to quickly access them.
You have probably seen some common widgets, such as music widget, weather
widget, clock widget e.t.c
Widgets could be of many types such as information widgets, collection
widgets, control widgets and hybrid widgets. Android provides us a complete
framework to develop our own widgets.
Widget - XML file
In order to create an application widget, first thing you need is
AppWidgetProviderInfo object, which you will define in a separate widget XML
file. In order to do that, right click on your project and create a new folder
called xml. Now right click on the newly created folder and create a new XML
file. The resource type of the XML file should be set to AppWidgetProvider. In
the xml file, define some properties which are as follows –
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dp"
android:updatePeriodMillis="0"
android:minHeight="146dp"
android:initialLayout="@layout/activity_main">
</appwidget-provider>
Widget - Layout file
Now you have to define the layout of your widget in your default XML file. You
can drag components to generate auto xml.
Widget - Java file
After defining layout, now create a new JAVA file or use existing one, and
extend it with AppWidgetProvider class and override its update method as
follows.
In the update method, you have to define the object of two classes which are
PendingIntent and RemoteViews.
Its syntax is −
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);
In the end you have to call an update method updateAppWidget() of the
AppWidgetManager class.
Its syntax is −
appWidgetManager.updateAppWidget(currentWidgetId,views);
A part from the updateAppWidget method, there are other methods defined in
this class to manipulate widgets.
They are as follows –
Sr.No Method & Description
1 onDeleted(Context context, int[] appWidgetIds)
This is called when an instance of AppWidgetProvider is deleted.
2 onDisabled(Context context)
This is called when the last instance of AppWidgetProvider is deleted
3 onEnabled(Context context)
This is called when an instance of AppWidgetProvider is created.
4 onReceive(Context context, Intent intent)
It is used to dispatch calls to the various methods of the class
Widget - Manifest file
You also have to declare the AppWidgetProvider class in your manifest file as
follows:
<receiver android:name="ExampleAppWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/example_appwidget_info" />
</receiver>
2. Study of android lifecycle and demonstration of it.
In Android, an activity is referred to as one screen in an application. It is very
similar to a single window of any desktop application. An Android app consists
of one or more screens or activities.
Each activity goes through various stages or a lifecycle and is managed by
activity stacks. So when a new activity starts, the previous one always remains
below it. There are four stages of an activity.
1. If an activity is in the foreground of the screen i.e at the top of the stack,
then it is said to be active or running. This is usually the activity that the user
is currently interacting with.
2. If an activity has lost focus and a non-full-sized or transparent activity has
focused on top of your activity. In such a case either another activity has a
higher position in multi-window mode or the activity itself is not focusable in
the current window mode. Such activity is completely alive.
3. If an activity is completely hidden by another activity, it is stopped or
hidden. It still retains all the information, and as its window is hidden thus it
will often be killed by the system when memory is needed elsewhere.
4. The system can destroy the activity from memory by either asking it to
finish or simply killing its process. When it is displayed again to the user, it
must be completely restarted and restored to its previous state.
For each stage, android provides us with a set of 7 methods that have their own
significance for each stage in the life cycle. The image shows a path of
migration whenever an app switches from one state to another.
Demo Android App to Demonstrate Activity Lifecycle in Android
File: MainActivity.java
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);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",
Toast.LENGTH_LONG).show();
}
protected void onStart() {
super.onStart();
Toast toast = Toast.makeText(getApplicationContext(), "onStart Called",
Toast.LENGTH_LONG).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called",
Toast.LENGTH_LONG).show();
}
protected void onPause() {
super.onPause();
Toast toast = Toast.makeText(getApplicationContext(), "onPause Called",
Toast.LENGTH_LONG).show();
}
protected void onResume() {
super.onResume();
Toast toast = Toast.makeText(getApplicationContext(), "onResume Called",
Toast.LENGTH_LONG).show();
}
protected void onStop() {
super.onStop();
Toast toast = Toast.makeText(getApplicationContext(), "onStop Called",
Toast.LENGTH_LONG).show();
}
protected void onDestroy() {
super.onDestroy();
Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called",
Toast.LENGTH_LONG).show();
}
}
3. Study of Different Layouts
Android Layout is used to define the user interface that holds the UI controls
or widgets that will appear on the screen of an android application or activity
screen. Generally, every application is a combination of View and ViewGroup.
As we know, an android application contains a large number of activities and
we can say each activity is one page of the application. So, each activity
contains multiple user interface components and those components are the
instances of the View and ViewGroup. All the elements in a layout are built
using a hierarchy of View and ViewGroup objects.
View:
A View is defined as the user interface which is used to
create interactive UI components such
as TextView, ImageView, EditText, RadioButton, etc.,
and is responsible for event handling and drawing. They
are Generally Called Widgets.
View:
A ViewGroup act as a base class for layouts and layouts
parameters that hold other Views or ViewGroups and to
define the layout properties. They are Generally Called
layouts.
ViewGroup :
The Android framework will allow us to use UI elements or widgets in two
ways:
1. Use UI elements in the XML file
2. Create elements in the Kotlin file dynamically
Types of Android Layout
 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to
provide child View elements one by one either in a particular direction
either horizontally or vertically based on the orientation property.
 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used
to specify the position of child View elements relative to each other like (A
to the right of B) or relative to the parent (fix to the top of the parent).
 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass,
used to specify the position of layout constraints for every child View
relative to other views present. A ConstraintLayout is similar to a
RelativeLayout, but having more power.
 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to
specify the position of View elements it contains on the top of each other
to display only a single View inside the FrameLayout.
 Android Table Layout: TableLayout is a ViewGroup subclass, used to
display the child View elements in rows and columns.
 Android Web View: WebView is a browser that is used to display the
web pages in our activity layout.
 Android ListView: ListView is a ViewGroup, used to display scrollable
lists of items in a single column.
 Android Grid View: GridView is a ViewGroup that is used to display a
scrollable list of items in a grid view of rows and columns.
4. To build Calculator App using Linear Layouts
The complete interface code of 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:paddingLeft="@dimen/activity_horizontal_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:textStyle="bold|italic"
android:fontFamily="serif"
android:visibility="visible"
android:textSize="24sp"
android:layout_weight="0.07" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/editOp1"
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:text="-"
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:text="@string/result"
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>
So now we have designed the complete UI of the Calculator App.
File: MainActivity.java
package abhiandroid.com.calculater;
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 opr1;
private EditText opr2;
private Button btnadd;
private Button btnsub;
private Button btnmul;
private Button btndiv;
private Button btnclr;
private TextView txtresult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
opr1 = (EditText) findViewById(R.id.editOp1);
opr2 = (EditText) findViewById(R.id.editOp2);
btnadd = (Button) findViewById(R.id.btnadd);
btnsub = (Button) findViewById(R.id.btnsub);
btnmul = (Button) findViewById(R.id.btnmul);
btndiv = (Button) findViewById(R.id.btndiv);
btnclr = (Button) findViewById(R.id.btnclr);
txtresult= (TextView) findViewById(R.id.result);
// Addition
btnadd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((opr1.getText().length()>0) && (opr2.getText().length()>0))
{
double oper1 = Double.parseDouble(opr1.getText().toString());
double oper2 = Double.parseDouble(opr2.getText().toString());
double result = oper1 + oper2;
txtresult.setText(Double.toString(result));
}
else{
Toast toast= Toast.makeText(MainActivity.this,"Enter The Required
Numbers",Toast.LENGTH_LONG);
toast.show();
}
}
});
//Subtraction
btnsub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((opr1.getText().length()>0) && (opr2.getText().length()>0))
{
double oper1 = Double.parseDouble(opr1.getText().toString());
double oper2 = Double.parseDouble(opr2.getText().toString());
double result = oper1 - oper2;
txtresult.setText(Double.toString(result));
}
else{
Toast toast= Toast.makeText(MainActivity.this,"Enter The Required
Numbers",Toast.LENGTH_LONG);
toast.show();
}
}
});
// Multiplication
btnmul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((opr1.getText().length()>0) && (opr2.getText().length()>0))
{
double oper1 = Double.parseDouble(opr1.getText().toString());
double oper2 = Double.parseDouble(opr2.getText().toString());
double result = oper1 * oper2;
txtresult.setText(Double.toString(result));
}
else{
Toast toast= Toast.makeText(MainActivity.this,"Enter The Required
Numbers",Toast.LENGTH_LONG);
toast.show();
}
}
});
// Division
btndiv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((opr1.getText().length()>0) && (opr2.getText().length()>0))
{
double oper1 = Double.parseDouble(opr1.getText().toString());
double oper2 = Double.parseDouble(opr2.getText().toString());
double result = oper1 / oper2;
txtresult.setText(Double.toString(result));
}
else{
Toast toast= Toast.makeText(MainActivity.this,"Enter The Required
Numbers",Toast.LENGTH_LONG);
toast.show();
}
}
});
// Reset Feilds
btnclr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
opr1.setText("");
opr2.setText("");
txtresult.setText("0.00");
opr1.requestFocus();
}
});
}
}
5. To Build Login App using different Layouts
MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.graphics.Color;
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 Activity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
b2 = (Button)findViewById(R.id.button2);
tx1 = (TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Wrong
Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
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" android:paddingLeft=
"@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
android:paddingBottom = "@dimen/activity_vertical_margin" tools:context = ".MainActivity">
<TextView android:text = "Login" android:layout_width="wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/textview"
android:textSize = "35dp"
android:layout_alignParentTop = "true"
android:layout_centerHorizontal = "true" />
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Tutorials point"
android:id = "@+id/textView"
android:layout_below = "@+id/textview"
android:layout_centerHorizontal = "true"
android:textColor = "#ff7aff24"
android:textSize = "35dp" />
<EditText
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:id = "@+id/editText"
android:hint = "Enter Name"
android:focusable = "true"
android:textColorHighlight = "#ff7eff15"
android:textColorHint = "#ffff25e6"
android:layout_marginTop = "46dp"
android:layout_below = "@+id/imageView"
android:layout_alignParentLeft = "true"
android:layout_alignParentStart = "true"
android:layout_alignParentRight = "true"
android:layout_alignParentEnd = "true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText"
android:textColorHint="#ffff299f"
android:hint="Password" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attempts Left:"
android:id="@+id/textView2"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView3"
android:layout_alignTop="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="@+id/textView2"
android:layout_toEndOf="@+id/textview"
android:textSize="25dp"
android:layout_toRightOf="@+id/textview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/textview"
android:layout_toStartOf="@+id/textview" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="@+id/button2"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/textview"
android:layout_toEndOf="@+id/textview" />
</RelativeLayout>
Following is the content of the res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
6. To Build a Stopwatch Application
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"
<!-- Add some background color -->
android:background="#0F9D58"
android:padding="16dp"
tools:context="org.geeksforgeeks.stopwatch.StopwatchActivity">
<TextView
<!-- We will use text view "time_view" -->
<!-- to display the number of seconds. -->
android:id="@+id/time_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
<!-- These below attributes make the stopwatch -->
<!-- timer nice and big. -->
android:textAppearance="@android:style/TextAppearance.Large"
android:textSize="56sp" />
<Button
<!-- This code is for the Start button.
android:id="@+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
<!-- When it gets clicked, the Start button -->
<!-- calls the onClickStart() method. -->
android:onClick="onClickStart"
android:text="@string/start" />
<Button
<!-- This code is for the Stop button. -->
android:id="@+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
<!-- When it gets clicked, the Stop button -->
<!-- calls the onClickStop() method. -->
android:onClick="onClickStop"
android:text="@string/stop" />
<Button
<!-- This code is for Reset button. -->
android:id="@+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
<!-- When it gets clicked, the Reset button -->
<!-- calls the onClickReset() method. -->
android:onClick="onClickReset"
android:text="@string/reset" />
</LinearLayout>
MainActivity.java.
package org.geeksforgeeks.stopwatch;
import android.app.Activity;
import android.os.Handler;
import android.view.View;
import android.os.Bundle;
import java.util.Locale;
import android.widget.TextView;
public class StopwatchActivity extends Activity {
// Use seconds, running and wasRunning respectively
// to record the number of seconds passed,
// whether the stopwatch is running and
// whether the stopwatch was running
// before the activity was paused.
// Number of seconds displayed
// on the stopwatch.
private int seconds = 0;
// Is the stopwatch running?
private boolean running;
private boolean wasRunning;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
if (savedInstanceState != null) {
// Get the previous state of the stopwatch
// if the activity has been
// destroyed and recreated.
seconds
= savedInstanceState
.getInt("seconds");
running
= savedInstanceState
.getBoolean("running");
wasRunning
= savedInstanceState
.getBoolean("wasRunning");
}
runTimer();
}
// Save the state of the stopwatch
// if it's about to be destroyed.
@Override
public void onSaveInstanceState(
Bundle savedInstanceState)
{
savedInstanceState
.putInt("seconds", seconds);
savedInstanceState
.putBoolean("running", running);
savedInstanceState
.putBoolean("wasRunning", wasRunning);
}
// If the activity is paused,
// stop the stopwatch.
@Override
protected void onPause()
{
super.onPause();
wasRunning = running;
running = false;
}
// If the activity is resumed,
// start the stopwatch
// again if it was running previously.
@Override
protected void onResume()
{
super.onResume();
if (wasRunning) {
running = true;
}
}
// Start the stopwatch running
// when the Start button is clicked.
// Below method gets called
// when the Start button is clicked.
public void onClickStart(View view)
{
running = true;
}
// Stop the stopwatch running
// when the Stop button is clicked.
// Below method gets called
// when the Stop button is clicked.
public void onClickStop(View view)
{
running = false;
}
// Reset the stopwatch when
// the Reset button is clicked.
// Below method gets called
// when the Reset button is clicked.
public void onClickReset(View view)
{
running = false;
seconds = 0;
}
// Sets the NUmber of seconds on the timer.
// The runTimer() method uses a Handler
// to increment the seconds and
// update the text view.
private void runTimer()
{
// Get the text view.
final TextView timeView
= (TextView)findViewById(
R.id.time_view);
// Creates a new Handler
final Handler handler
= new Handler();
// Call the post() method,
// passing in a new Runnable.
// The post() method processes
// code without a delay,
// so the code in the Runnable
// will run almost immediately.
handler.post(new Runnable() {
@Override
public void run()
{
int hours = seconds / 3600;
int minutes = (seconds % 3600) / 60;
int secs = seconds % 60;
// Format the seconds into hours, minutes,
// and seconds.
String time
= String
.format(Locale.getDefault(),
"%d:%02d:%02d", hours,
minutes, secs);
// Set the text view text.
timeView.setText(time);
// If running is true, increment the
// seconds variable.
if (running) {
seconds++;
}
// Post the code again
// with a delay of 1 second.
handler.postDelayed(this, 1000);
}
});
}
}
7. To Build a Business Visiting Card
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/jalogo" />
<TextView
android:id="@+id/nameField"
style="@style/TextAppearance.AppCompat.Headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="JANE APPLESEED"
android:textColor="@color/colorPrimaryDark"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />
<TextView
android:id="@+id/titleField"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:text="Educator"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/nameField" />
<View
android:id="@+id/horizontalLine"
android:layout_width="300dp"
android:layout_height="2dp"
android:layout_marginTop="96dp"
android:background="@color/colorPrimaryDark"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/titleField" />
<TextView
android:id="@+id/phoneField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="+123 4567890"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/horizontalLine" />
<TextView
android:id="@+id/emailField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="janeappleseed@gmail.com"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.485"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/phoneField" />
<TextView
android:id="@+id/locationField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="California, USA"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.492"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/emailField" />
<TextView
android:id="@+id/websiteField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:text="janeappleseed.com"
android:textColor="@color/colorPrimaryDark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/locationField"
app:layout_constraintVertical_bias="1.0" />
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#009688</color>
<color name="colorPrimaryDark">#00675b</color>
<color name="colorPrimaryLight">#52c7b8</color>
<color name="colorAccent">#03DAC5</color>
</resources>
8. To Study and Build Applications using Intents
Android uses Intent for communicating between the components of an
Application and also from one application to another application.
Intent are the objects which is used in android for passing the information
among Activities in an Application and from one app to another also. Intent are
used for communicating between the Application components and it also
provides the connectivity between two apps.
Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent
Explicit Intent:
Explicit Intents are used to connect the application internally.
In Explicit we use the name of component which will be affected by Intent. For
Example: If we know class name then we can navigate the app from One
Activity to another activity using Intent. In the similar way we can start a
service to download a file in background process.
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just
specify the Action which has to be performed and further this action is handled
by the component of another application.
The basic example of implicit Intent is to open any web page
Intent Example In Android:
The example will show you both implicit and explicit Intent together.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="If you click on Explicit example we will navigate to
second activity within App and if you click on Implicit example AbhiAndroid
Homepage will open in Browser"
android:id="@+id/textView2"
android:clickable="false"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp"
android:background="#3e7d02"
android:textColor="#ffffff" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/explicit_Intent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="147dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/implicit_Intent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Step 2: Design the UI of second activity activity_second.xml
Now lets design UI of another activity where user will navigate after he click on Explicit
Example button. Go to layout folder, create a new activity and name it
activity_second.xml.
 In this activity we will simply use TextView to tell user he is now on second
activity.
Below is the complete code of activity_second.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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#CCEEAA"
tools:context="com.example.android.intents.SecondActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is Second Activity"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Step 3: Implement onClick event for Implicit And Explicit Button inside
MainActivity.java
Now we will use setOnClickListener() method to implement OnClick event on
both the button. Implicit button will open AbhiAndroid.com homepage in
browser and Explicit button will move to SecondActivity.java.
Below is the complete code of MainActivity.java
package com.example.android.intents;
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;
public class MainActivity extends AppCompatActivity {
Button explicit_btn, implicit_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
explicit_btn = (Button)findViewById(R.id.explicit_Intent);
implicit_btn = (Button) findViewById(R.id.implicit_Intent);
//implement Onclick event for Explicit Intent
explicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),
SecondActivity.class);
startActivity(intent);
}
});
//implement onClick event for Implicit Intent
implicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.abhiandroid.com"));
startActivity(intent);
}
});
}
}
Step 4: Create A New JAVA class name SecondActivity
Now we need to create another SecondActivity.java which will simply open the
layout of activity_second.xml . Also we will use Toast to display message that he
is on second activity.
Below is the complete code of SecondActivity.java:
package com.example.android.intents;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toast.makeText(getApplicationContext(), "We are moved to second
Activity",Toast.LENGTH_LONG).show();
}
}
9. To Build Quiz App
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!--Using linear layout with vertical orientation and center gravity -->
<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:background="#FFFFFF"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<!--ImageView used for showing pictures along with questions-->
<ImageView
android:id="@+id/myimage"
android:layout_width="wrap_content"
android:src="@drawable/f1"
android:layout_height="wrap_content"/>
<!--TextView used for showing questions on screen-->
<TextView
android:id="@+id/answer_text_view"
android:text="@string/a"
android:textColor="@android:color/black"
android:textSize="30sp"
android:padding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<!--Using another LinearLayout for showing buttons
in horizontal orientation-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!--TrueButton-->
<Button
android:id="@+id/true_button"
android:layout_marginRight="20dp"
android:backgroundTint="#5BD91B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="@string/true_text" />
<!--FalseButton-->
<Button
android:id="@+id/false_button"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:backgroundTint="#E33328"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="@string/false_text" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!--PreviousButton-->
<ImageButton
android:id="@+id/prev_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/baseline_keyboard_arrow_left_black_18dp"
android:backgroundTint="#DFD2D1"
android:text="@string/prev_text" />
<!--NextButton-->
<ImageButton
android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#DFD2D1"
android:src="@drawable/baseline_keyboard_arrow_right_black_18dp"
android:text="@string/next_text" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package org.geeksforgeeks.quizapp;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
// setting up things
private Button falseButton;
private Button trueButton;
private ImageButton nextButton;
private ImageButton prevButton;
private ImageView Image;
private TextView questionTextView;
private int correct = 0;
// to keep current question track
private int currentQuestionIndex = 0;
private Question[] questionBank = new Question[] {
// array of objects of class Question
// providing questions from string
// resource and the correct ans
new Question(R.string.a, true),
new Question(R.string.b, false),
new Question(R.string.c, true),
new Question(R.string.d, true),
new Question(R.string.e, true),
new Question(R.string.f, false),
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// setting up the buttons
// associated with id
falseButton = findViewById(R.id.false_button);
trueButton = findViewById(R.id.true_button);
nextButton = findViewById(R.id.next_button);
prevButton = findViewById(R.id.prev_button);
// register our buttons to listen to
// click events
questionTextView
= findViewById(R.id.answer_text_view);
Image = findViewById(R.id.myimage);
falseButton.setOnClickListener(this);
trueButton.setOnClickListener(this);
nextButton.setOnClickListener(this);
prevButton.setOnClickListener(this);
}
@SuppressLint("SetTextI18n")
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onClick(View v)
{
// checking which button is
// clicked by user
// in this case user choose false
switch (v.getId()) {
case R.id.false_button:
checkAnswer(false);
break;
case R.id.true_button:
checkAnswer(true);
break;
case R.id.next_button:
// go to next question
// limiting question bank range
if (currentQuestionIndex < 7) {
currentQuestionIndex
= currentQuestionIndex + 1;
// we are safe now!
// last question reached
// making buttons
// invisible
if (currentQuestionIndex == 6) {
questionTextView.setText(getString(
R.string.correct, correct));
nextButton.setVisibility(
View.INVISIBLE);
prevButton.setVisibility(
View.INVISIBLE);
trueButton.setVisibility(
View.INVISIBLE);
falseButton.setVisibility(
View.INVISIBLE);
if (correct > 3)
questionTextView.setText(
"CORRECTNESS IS " + correct
+ " "
+ "OUT OF 6");
// showing correctness
else
Image.setImageResource(
R.drawable.resu);
// if correctness<3 showing sad emoji
}
else {
updateQuestion();
}
}
break;
case R.id.prev_button:
if (currentQuestionIndex > 0) {
currentQuestionIndex
= (currentQuestionIndex - 1)
% questionBank.length;
updateQuestion();
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void updateQuestion()
{
Log.d("Current",
"onClick: " + currentQuestionIndex);
questionTextView.setText(
questionBank[currentQuestionIndex]
.getAnswerResId());
// setting the textview with new question
switch (currentQuestionIndex) {
case 1:
// setting up image for each
// question
Image.setImageResource(R.drawable.f2);
break;
case 2:
Image.setImageResource(R.drawable.f3);
break;
case 3:
Image.setImageResource(R.drawable.f4);
break;
case 4:
Image.setImageResource(R.drawable.f5);
break;
case 5:
Image.setImageResource(R.drawable.f6);
break;
case 6:
Image.setImageResource(R.drawable.f7);
break;
case 7:
Image.setImageResource(R.drawable.f1);
break;
}
}
private void checkAnswer(boolean userChooseCorrect)
{
boolean answerIsTrue
= questionBank[currentQuestionIndex]
.isAnswerTrue();
// getting correct ans of current question
int toastMessageId;
// if ans matches with the
// button clicked
if (userChooseCorrect == answerIsTrue) {
toastMessageId = R.string.correct_answer;
correct++;
}
else {
// showing toast
// message correct
toastMessageId = R.string.wrong_answer;
}
Toast
.makeText(MainActivity.this, toastMessageId,
Toast.LENGTH_SHORT)
.show();
}
}
10.To Build Tic Tac Toe Game
activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:background="@color/green"
tools:context=".MainActivity">
<!--title text-->
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="23dp"
android:text="GFG Tic Tac Toe"
android:textSize="45sp"
android:textStyle="bold"
app:fontFamily="cursive"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!--image of the grid-->
<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:contentDescription="Start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:srcCompat="@drawable/grid" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="0dp"
android:layout_height="420dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="@+id/imageView"
app:layout_constraintEnd_toEndOf="@+id/imageView"
app:layout_constraintStart_toStartOf="@+id/imageView"
app:layout_constraintTop_toTopOf="@+id/imageView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<!--images of the grid boxes-->
<ImageView
android:id="@+id/imageView0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="0" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="1" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="3" />
<ImageView
android:id="@+id/imageView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="4" />
<ImageView
android:id="@+id/imageView5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="5" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="6" />
<ImageView
android:id="@+id/imageView7"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="7" />
<ImageView
android:id="@+id/imageView8"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="playerTap"
android:padding="20sp"
android:tag="8" />
</LinearLayout>
</LinearLayout>
<!--game status text display-->
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15sp"
android:text="Status"
android:textSize="28sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/linearLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
boolean gameActive = true;
// Player representation
// 0 - X
// 1 - O
int activePlayer = 0;
int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2};
// State meanings:
// 0 - X
// 1 - O
// 2 - Null
// put all win positions in a 2D array
int[][] winPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 3, 6}, {1, 4, 7}, {2, 5, 8},
{0, 4, 8}, {2, 4, 6}};
public static int counter = 0;
// this function will be called every time a
// players tap in an empty box of the grid
public void playerTap(View view) {
ImageView img = (ImageView) view;
int tappedImage = Integer.parseInt(img.getTag().toString());
// game reset function will be called
// if someone wins or the boxes are full
if (!gameActive) {
gameReset(view);
}
// if the tapped image is empty
if (gameState[tappedImage] == 2) {
// increase the counter
// after every tap
counter++;
// check if its the last box
if (counter == 9) {
// reset the game
gameActive = false;
}
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.doc
ANDROID LAB MANUAL.doc

More Related Content

What's hot

NFS(Network File System)
NFS(Network File System)NFS(Network File System)
NFS(Network File System)udamale
 
Grafana introduction
Grafana introductionGrafana introduction
Grafana introductionRico Chen
 
Universal metrics with Apache Beam
Universal metrics with Apache BeamUniversal metrics with Apache Beam
Universal metrics with Apache BeamEtienne Chauchot
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systemssumitjain2013
 
Backup and recovery
Backup and recoveryBackup and recovery
Backup and recoverydhawal mehta
 
A Kafka Client’s Request: There and Back Again with Danica Fine
A Kafka Client’s Request: There and Back Again with Danica FineA Kafka Client’s Request: There and Back Again with Danica Fine
A Kafka Client’s Request: There and Back Again with Danica FineHostedbyConfluent
 
Software Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationSoftware Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationAjit Nayak
 
Chapter 13 software testing strategies
Chapter 13 software testing strategiesChapter 13 software testing strategies
Chapter 13 software testing strategiesSHREEHARI WADAWADAGI
 
Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Mayank Shrivastava
 
Introduction to Software Engineering
Introduction to Software EngineeringIntroduction to Software Engineering
Introduction to Software EngineeringZahoor Khan
 
04. availability-concepts
04. availability-concepts04. availability-concepts
04. availability-conceptsMuhammad Ahad
 
Cloud computing (IT-703) UNIT 1 & 2
Cloud computing (IT-703) UNIT 1 & 2Cloud computing (IT-703) UNIT 1 & 2
Cloud computing (IT-703) UNIT 1 & 2Jitendra s Rathore
 
Software architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding GuideSoftware architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding GuideMohammed Fazuluddin
 
Non Functional Requirement.
Non Functional Requirement.Non Functional Requirement.
Non Functional Requirement.Khushboo Shaukat
 
network monitoring system ppt
network monitoring system pptnetwork monitoring system ppt
network monitoring system pptashutosh rai
 

What's hot (20)

Systems Administration
Systems AdministrationSystems Administration
Systems Administration
 
NFS(Network File System)
NFS(Network File System)NFS(Network File System)
NFS(Network File System)
 
Grafana introduction
Grafana introductionGrafana introduction
Grafana introduction
 
Universal metrics with Apache Beam
Universal metrics with Apache BeamUniversal metrics with Apache Beam
Universal metrics with Apache Beam
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systems
 
Backup and recovery
Backup and recoveryBackup and recovery
Backup and recovery
 
A Kafka Client’s Request: There and Back Again with Danica Fine
A Kafka Client’s Request: There and Back Again with Danica FineA Kafka Client’s Request: There and Back Again with Danica Fine
A Kafka Client’s Request: There and Back Again with Danica Fine
 
Software Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & SpecificationSoftware Engineering : Requirement Analysis & Specification
Software Engineering : Requirement Analysis & Specification
 
Chapter 13 software testing strategies
Chapter 13 software testing strategiesChapter 13 software testing strategies
Chapter 13 software testing strategies
 
Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020
 
Introduction to Software Engineering
Introduction to Software EngineeringIntroduction to Software Engineering
Introduction to Software Engineering
 
04. availability-concepts
04. availability-concepts04. availability-concepts
04. availability-concepts
 
Basics of the Web Platform
Basics of the Web PlatformBasics of the Web Platform
Basics of the Web Platform
 
Cloud computing (IT-703) UNIT 1 & 2
Cloud computing (IT-703) UNIT 1 & 2Cloud computing (IT-703) UNIT 1 & 2
Cloud computing (IT-703) UNIT 1 & 2
 
Grafana.pptx
Grafana.pptxGrafana.pptx
Grafana.pptx
 
Software architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding GuideSoftware architectural patterns - A Quick Understanding Guide
Software architectural patterns - A Quick Understanding Guide
 
Software Metrics
Software MetricsSoftware Metrics
Software Metrics
 
Analysis modelling
Analysis modellingAnalysis modelling
Analysis modelling
 
Non Functional Requirement.
Non Functional Requirement.Non Functional Requirement.
Non Functional Requirement.
 
network monitoring system ppt
network monitoring system pptnetwork monitoring system ppt
network monitoring system ppt
 

Similar to ANDROID LAB MANUAL.doc

Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1Amit Saxena
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginnersJavaTpoint.Com
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android DevelopmentAly Abdelkareem
 
Android terminologies
Android terminologiesAndroid terminologies
Android terminologiesjerry vasoya
 
What is Android?
What is Android?What is Android?
What is Android?ndalban
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answerskavinilavuG
 
Android Tutorial
Android TutorialAndroid Tutorial
Android TutorialFun2Do Labs
 
OS in mobile devices [Android]
OS in mobile devices [Android]OS in mobile devices [Android]
OS in mobile devices [Android]Yatharth Aggarwal
 
Nativa Android Applications development
Nativa Android Applications developmentNativa Android Applications development
Nativa Android Applications developmentAlfredo Morresi
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesAhsanul Karim
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesAhsanul Karim
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32Eden Shochat
 
Password security system for websites
Password security system for websitesPassword security system for websites
Password security system for websitesMike Taylor
 

Similar to ANDROID LAB MANUAL.doc (20)

Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1Android Tutorial For Beginners Part-1
Android Tutorial For Beginners Part-1
 
Notes Unit3.pptx
Notes Unit3.pptxNotes Unit3.pptx
Notes Unit3.pptx
 
Android user interface design-chapter13
Android user interface design-chapter13Android user interface design-chapter13
Android user interface design-chapter13
 
Get an Android tutorial for beginners
Get an Android tutorial for beginnersGet an Android tutorial for beginners
Get an Android tutorial for beginners
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Android terminologies
Android terminologiesAndroid terminologies
Android terminologies
 
What is Android?
What is Android?What is Android?
What is Android?
 
Android interview questions and answers
Android interview questions and answersAndroid interview questions and answers
Android interview questions and answers
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
 
OS in mobile devices [Android]
OS in mobile devices [Android]OS in mobile devices [Android]
OS in mobile devices [Android]
 
Android beginners David
Android beginners DavidAndroid beginners David
Android beginners David
 
Nativa Android Applications development
Nativa Android Applications developmentNativa Android Applications development
Nativa Android Applications development
 
Unit2
Unit2Unit2
Unit2
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
 
Day 3: Getting Active Through Activities
Day 3: Getting Active Through ActivitiesDay 3: Getting Active Through Activities
Day 3: Getting Active Through Activities
 
Android app development
Android app developmentAndroid app development
Android app development
 
UIAutomator
UIAutomatorUIAutomator
UIAutomator
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 
Password security system for websites
Password security system for websitesPassword security system for websites
Password security system for websites
 
Android
AndroidAndroid
Android
 

Recently uploaded

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

ANDROID LAB MANUAL.doc

  • 1. PRACTICAL JOURNAL OF ANDROID PROGRAMMING BE : VI Semester Department of Computer Science and Information Technology Name : Palak Jaiswal Branch : CI Section : 2 Roll No. : 0827CI201126 Session : Jan-Jun 2023 Department of Computer Science and Information Technology ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH, INDORE
  • 2. Department of Computer Science Engineering Certificate This is to certify that the experimental work entered in this journal as per the B.Tech III year syllabus prescribed by the RGPV was done by Ms. Palak Jaiswal B.Tech-VI semester CI in the Android Programming Laboratory of this institute during the academic year 2023. Signature of Faculty
  • 3. LAB INDEX 1. Introduction to android operating system and study of basic widgets. 2. Study of android lifecycle and demonstration of it. 3. Study of Different Layouts 4. To build Calculator App using Linear Layouts 5. To Build Login App using different Layouts 6. To Build a Stop Watch Application 7. To Build a Business Visiting Card 8. To Study and Build Applications using Intents 9. To Build Quiz App 10.To Build Tic Tac Game
  • 4. Assignment 1 Aim: Introduction to android Objective: Student should get the knowledge of android operating system background. Outcome: Student will be aware of the android operating system. 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
  • 5. a 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 Dalvik VM makes use of Linux core features like memory management and multi-threading, which is intrinsic in the Java language. The Dalvik VM enables every Android application to run in its own process, with its own instance of the Dalvik virtual machine. 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.
  • 6. 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. For example, a simple vertical layout with a text view and a button looks like this: <?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" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am a Button" />
  • 7. </LinearLayout> Android UI Controls There are number of UI controls provided by Android that allow you to build the graphical user interface for your app. S.N. UI Control & Description TextView 1 This control is used to display text to the user. EditText 2 EditText is a predefined subclass of TextView that includes rich editing capabilities. AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText, 3 except that it shows a list of completion suggestions automatically while the user is typing. Button 4 A push-button that can be pressed, or clicked, by the user to perform an action. ImageButton 5 AbsoluteLayout enables you to specify the exact location of its children. CheckBox An on/off switch that can be toggled by the user. You should 6 use checkboxes when presenting users with a group of selectable options that are not mutually exclusive. ToggleButton 7 An on/off button with a light indicator.
  • 8. RadioButton 8 The RadioButton has two states: either checked or unchecked. RadioGroup 9 A RadioGroup is used to group together one or more RadioButtons. ProgressBar The ProgressBar view provides visual feedback about some 10 ongoing tasks, such as when you are performing a task in the background. Spinner 11 A drop-down list that allows users to select one value from a set. TimePicker 12 The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode. DatePicker 13 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 as follows: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  • 9. android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am a TextView" /> </LinearLayout> Then finally create an instance of the Control object and capture it from the layout, use the following: TextView myText = (TextView) findViewById(R.id.text_id); Android Event Handling 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. There are following three concepts related to Android Event Management: • 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 happes.
  • 10. • 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. Event Listeners & Event Handlers Event Handler Event Listener & Description OnClickListener() onClick() This is called when the user either clicks or touches or focuses upon any widget like button, text, image etc. You will use onClick() event handler to handle such event. OnLongClickListener() This is called when the user either clicks or onLongClick() touches or focuses upon any widget like button, text, image etc. for one or more seconds. You will use onLongClick() event handler to handle such event. OnFocusChangeListener() onFocusChange() This is called when the widget looses its focus ie. user goes away from the view item. You will use onFocusChange() event handler to handle such event. OnFocusChangeListener() onKey() This is called when the user is focused on the item and presses or releases a hardware key on
  • 11. the device. You will use onKey() event handler to handle such event. OnTouchListener() onTouch() This is called when the user presses the key, releases the key, or any movement gesture on the screen. You will use onTouch() event handler to handle such event. OnMenuItemClickListener() onMenuItemClick() This is called when the user selects a menu item. You will use onMenuItemClick() event handler to handle such event. There are many more event listeners available as a part of View class like OnHoverListener, OnDragListener etc which may be needed for your application. So I recommend to refer official documentation for Android application development in case you are going to develop a sophisticated apps. Exercise: Key points to study: History, Versions, Architecture, IDE (Eclipse), SDK of android.
  • 12. Assignment 2 Aim: Study of UI in Android Objective: Student should be able to design their own UI for android application using XML. Outcome: Student will demonstrate the basic application using UI in android. Create Android Application The first step is to create a simple Android Application using Eclipse IDE. Follow the option File → New → Project and finally select → Android New Application wizard from the wizard list. Now name your application as HelloWorld using the wizard window as follows: 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:
  • 13. Anatomy of Android Application Before you run your app, you should be aware of a few directories and files in the Android project:
  • 14. S.N. Folder, File & Description 1 src This contains the .java source files for your project. By default, it
  • 15. 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 2 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 3 ADT during the build process and everything else needed to run an Android application. res/drawable-hdpi 4 This is a directory for drawable objects that are designed for high-density screens. res/layout 5 This is a directory for files that define your app's user interface. res/values 6 This is a directory for other various XML files that contain a collection of resources, such as strings and colors definitions. AndroidManifest.xml 7 This is the manifest file which describes the fundamental characteristics of the app and defines each of its components. Following section will give a brief overview few of the important application files. The Main Activity File The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik executable and runs
  • 16. your application. Following is the default code generated by the application wizard for Hello World! application: package com.example.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. TheonCreate() method is one of many methods that are fi red when an activity is loaded. The Manifest File Whatever component you develop as a part of your application, you must declare all its components in a manifest file called AndroidManifest.xml which ressides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloworld" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8"
  • 17. android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest> Here <application>...</application> tags enclosed the components related to the application. Attributeandroid:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders 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: <activity>elements for activities
  • 18. <service> elements for services <receiver> elements for broadcast receivers <provider> elements for content providers The Strings File 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> The R File The gen/com.example.helloworld/R.java file is the glue between the activity Java files likeMainActivity.java and the resources like strings.xml. It is an automatically generated file and you should not modify the content of the R.java file. Following is a sample of R.java file: /* 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.helloworld; public final class R { public static final class attr { } public static final class dimen { public static final int padding_large=0x7f040002; public static final int padding_medium=0x7f040001; public static final int padding_small=0x7f040000; }
  • 19. public static final class drawable { public static final int ic_action_search=0x7f020000; public static final int ic_launcher=0x7f020001; } public static final class id { public static final int menu_settings=0x7f080000; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class menu { public static final int activity_main=0x7f070000; } public static final class string { public static final int app_name=0x7f050000; public static final int hello_world=0x7f050001; public static final int menu_settings=0x7f050002; public static final int title_activity_main=0x7f050003; } public static final class style { public static final int AppTheme=0x7f060000; } } The Layout File The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!" application, this file will have following content related to default layout: <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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:padding="@dimen/padding_medium" android:text="@string/hello_world" tools:context=".MainActivity" />
  • 20. </RelativeLayout> This is an example of simple RelativeLayout which we will study in a separate chapter. 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!". Running the Application 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: Exercise: Key points to study: Package explorer (Description about folders e.g. src, gen,res, etc.), Description about XML file, Layouts.
  • 21. 1. Develop an application Hello world program description about tags used in XML File: activity_main.xml Android studio auto generates code for activity_main.xml file. <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.androi d.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="first.javatpoint.com.welcome.MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello Android!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> } File: MainActivity.java package first.javatpoint.com.welcome; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
  • 22. 2. Develop an application using basic controls like button, textview, edittext etc. e.g. application for calculator. File: 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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:ignore="ExtraText"> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="83dp" android:onClick="Add" android:text="ADD" /> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="82dp" android:onClick="Sub" android:text="SUBTRACT" /> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="105dp" android:onClick="Mult" android:text="MULTIPLY" /> <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="79dp" android:onClick="Div" android:text="DIVIDE" /> <EditText android:id="@+id/editTextNumber2" android:layout_width="match_parent" android:layout_height="64dp"
  • 23. android:ems="10" android:inputType="number" android:text="Enter Number" /> <EditText android:id="@+id/editTextNumber3" android:layout_width="match_parent" android:layout_height="73dp" android:ems="10" android:inputType="number" android:text="Enter Number" /> <EditText android:id="@+id/editTextNumber4" android:layout_width="match_parent" android:layout_height="76dp" android:ems="10" android:inputType="number" android:text="Answer" /> </LinearLayout> File: MainActivity.java package com.example.myapplication; import android.os.Bundle; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.View; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.example.myapplication.databinding.ActivityMainBinding; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; public class MainActivity extends AppCompatActivity { String TAG ="MainActivity";
  • 24. private AppBarConfiguration appBarConfiguration; private ActivityMainBinding binding; @Override protected void onCreate( Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i( TAG, "--onCreate--"); } public void Add(View v){ EditText et1=(EditText)findViewById(R.id.editTextNumber2); EditText et2=(EditText)findViewById(R.id.editTextNumber3); EditText et3=(EditText)findViewById(R.id.editTextNumber4); int n1= Integer.parseInt(et1.getText().toString()); int n2= Integer.parseInt(et2.getText().toString()); int result=n1+n2; et3.setText("Total Value" + result); } public void Sub(View v){ EditText et1=(EditText)findViewById(R.id.editTextNumber2); EditText et2=(EditText)findViewById(R.id.editTextNumber3); EditText et3=(EditText)findViewById(R.id.editTextNumber4); int n1= Integer.parseInt(et1.getText().toString()); int n2= Integer.parseInt(et2.getText().toString()); int result=n1-n2; et3.setText("Subtract Value" +result); } public void Mult(View v){ EditText et1=(EditText)findViewById(R.id.editTextNumber2); EditText et2=(EditText)findViewById(R.id.editTextNumber3); EditText et3=(EditText)findViewById(R.id.editTextNumber4); int n1= Integer.parseInt(et1.getText().toString()); int n2= Integer.parseInt(et2.getText().toString()); int result=n1*n2; et3.setText("Multiplication Value" +result); } public void Div(View v){ EditText et1=(EditText)findViewById(R.id.editTextNumber2); EditText et2=(EditText)findViewById(R.id.editTextNumber3); EditText et3=(EditText)findViewById(R.id.editTextNumber4); int n1= Integer.parseInt(et1.getText().toString()); int n2= Integer.parseInt(et2.getText().toString()); int result=n1/n2; et3.setText("Division Value" + result); } }
  • 25. Exercise 3 Aim: Study of Activity LifeCycle Objective: Student should get the knowledge of android activity lifecycle. Outcome: Student will demonstrate the Activity lifecycle through the application. Activity life cycle States of an activity An activity can be in different states depending how it is interacting with the user. These states are described by the following table. Table 1. Activity state State Description Running Paused Activity is visible and interacts with the user. Activity is still visible but partially obscured, instance is running but might be killed by the system. Stopped Killed Activity is not visible, instance is running but might be killed by the system. Activity has been terminated by the system of by a call to its finish() method.
  • 26. The live cycle methods The Android system defines a life-cycle for activities via predefined life- cycle methods. The most important methods are: Table 3. Important Activity lifecycle methods Method Purpose onCreate() onResume() onPause() Called then the activity is created. Used to initialize the activity, for example create the user interface. Called if the activity get visible again and the user starts interacting with the activity again. Used to initialize fields, register listeners, bind to services, etc. Called once another activity gets into the foreground. Always called before the activity is not visible anymore. Used to release resources or save application data. For example you unregister listeners, intent receivers, unbind from services or remove system service listeners. onStop() Called once the activity is no longer visible. Time or CPU intensive shut-down operations, such as writing information to a database should be down in the onStop() method. This method is guaranteed to be called as of API 11.
  • 27. The life cycle of an activity with its most important methods is displayed in the following diagram. Android has more life cycle methods but not all of these methods are guaranteed to be called. The onDestroy() method is not guaranteed to be called, hence you typically do not use it. Activity instance state Instance state of an activity which is required to restore the activity to the state in which the user left it. This is non-persistent application data that needs to be passed between activities restarts during a configuration change to restore user selections. The application is responsible for restoring its instance state.
  • 28. Assume for example the user scrolled through a ListView with thousands of items and the activity is recreated. Loosing the position in the list is annoying for the user, hence the position should be restored. The onSaveInstanceState() can be used to store this instance state as a Bundle. A Bundle can contain primitive data types, arrays, String and objects which are of the Parcelable or Serialisable type. The persisted Bundle data is passed at restart of the activity to the onCreate() method and onRestoreInstanceState() as parameter. If you override onSaveInstanceState() and onRestoreInstanceState() you should call the super implementation of it, because the default views of Android store their data via a call to View.onSaveInstanceState from the onSaveInstanceState() method of the activity. For example EditText stores its content via the default call of this method. The onRestoreInstanceState() or the onCreate() methods can be used to recreate the instance scope of an activity if it is restarted. Exercise: Key point to study: Description about Activity LifeCycle Develop an application demonstrating Activity LifeCycle File: MainActivity.java @Override protected void onCreate( Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i( TAG, "--onCreate--"); } protected void onStart() { super.onStart(); Log.i( TAG, "--onStart--"); }
  • 29. @Override protected void onRestart() { super.onRestart(); Log.i( TAG, "--onRestart--"); } @Override protected void onResume() { super.onResume(); Log.i( TAG, "--onResume--"); } @Override protected void onPause() { super.onPause(); Log.i( TAG, "--onPause--"); } @Override protected void onStop() { super.onStop(); Log.i( TAG, "--onStop--"); } @Override protected void onDestroy() { super.onDestroy(); Log.i( TAG, "--onDestroy--"); }
  • 30. File: activity_main.xml package com.example.myapplication; import android.os.Bundle; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.View; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.example.myapplication.databinding.ActivityMainBinding; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { String TAG ="MainActivity"; private AppBarConfiguration appBarConfiguration; private ActivityMainBinding binding;
  • 31. Assignment 4 Aim: Study of Intents in android 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 Intents and intent filter What are intents? Intents are asynchronous messages which allow application components to request functionality from other Android components. Intents allow you to interact with components from the same applications as well as with components contributed by other applications. For example, an activity can start an external activity for taking a picture. Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining the components you are targeting. For example, via the startActivity() method you can define that the intent should be used to start an activity. An intent can contain data via a Bundle. This data can be used by the receiving component. Starting activities. To start an activity, use the method startActivity(intent). This method is defined on the Context object which activity extends.
  • 32. The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo.class); startActivity(i); Sub-activities Activities which are started by other Android activities are called sub-activities. This wording makes it easier to describe which activity is meant. Starting services You can also start services via intents. Use the startService(Intent) method call for that.
  • 33. Different types of intents Android supports explicit and implicit intents. An application can define the target component directly in the intent (explicit intent) or ask the Android system to evaluate registered components based on the intent data (implicit intents). Explicit Intents Explicit intents explicitly define the component which should be called by the Android system, by using the Java class as identifier. The following shows how to create an explicit intent and send it to the Android system. If the class specified in the intent represents an activity, the Android system starts it. Intent i = new Intent(this, ActivityTwo.class); i.putExtra("Value1", "This value one for ActivityTwo "); i.putExtra("Value2", "This value two ActivityTwo"); Explicit intents are typically used within on application as the classes in an application are controlled by the application developer. Implicit Intents Implicit intents specify the action which should be performed and optionally data which provides content for the action. For example, the following tells the Android system to view a webpage. All installed web browsers should be registered to the corresponding intent data via an intent filter. Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.exercise.com"));
  • 34. startActivity(i); If an implicit intent is sent to the Android system, it searches for all components which are registered for the specific action and the fitting data type. If only one component is found, Android starts this component directly. If several components are identified by the Android system, the user will get a selection dialog and can decide which component should be used for the intent. Data transfer between activities Data transfer to the target component: An intent contains certain header data, e.g., the desired action, the type, etc. Optionally an intent can also contain additional data based on an instance of the Bundle class which can be retrieved from the intent via the getExtras() method. You can also add data directly to the Bundle via the overloaded putExtra() methods of the Intent objects. Extras are key/value pairs. The key is always of type String. As value you can use the primitive data types (int, float, ...) plus objects of type String, Bundle, Parceable and Serializable. The receiving component can access this information via the getAction() and getData() methods on the Intent object. ThisIntent object can be retrieved via the getIntent() method. The component which receives the intent can use the getIntent().getExtras() method call to get the extra data. That is demonstrated in the following code snippet. Bundle extras = getIntent().getExtras(); if (extras == null) { return; }
  • 35. // get data via the key String value1 = extras.getString(Intent.EXTRA_TEXT); if (value1 != null) { // do something with the data } Example: Using the share intent Lots of Android applications allow you to share some data with other people, e.g., the Facebook, G+, Gmail and Twitter application. You can send data to one of these components. The following code snippet demonstrates the usage of such an intent within your application. // this runs, for example, af ter a button click Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!"); startActivity(intent); Retrieving result data from a sub-activity An activity can be closed via the back button on the phone. In this case the finish() method is performed. If the activity was started with the startActivity(Intent) method call, the caller requires no result or feedback from the activity which now is closed. If you start the activity with the startActivityForResult() method call, you expect feedback from the sub-activity. Once the sub-activity ends, the onActivityResult() method on the sub-activity is called and you can perform actions based on the result.
  • 36. In the startActivityForResult() method call you can specify a result code to determine which activity you started. This result code is returned to you. The started activity can also set a result code which the caller can use to determine if the activity was canceled or not. T he sub-activity uses the finish() method to create a new intent and to put data into it. It also sets a result via the setResult()method call. The following example code demonstrates how to trigger an intent with the startActivityForResult() method.
  • 37. public void onClick(View view) { Intent i = new Intent(this, ActivityTwo.class); i.putExtra("Value1", "This value one for ActivityTwo "); i.putExtra("Value2", "This value two ActivityTwo"); // set the request code to any code you like, // you can identif y the callback via this code startActivityForResult(i, REQUEST_CODE); } If you use the startActivityForResult() method, then the started activity is called a sub-activity. If the sub-activity is finished, it can send data back to its caller via an Intent. This is done in the finish() method. @Override public void finish() { // Prepare data intent Intent data = new Intent(); data.putExtra("returnKey1", "Swinging on a star. "); data.putExtra("returnKey2", "You could be better then you are. "); // Activity f inished ok, return the data setResult(RESULT_OK, data); super.finish(); } Once the sub-activity finishes, the onActivityResult() method in the calling activity is called. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  • 38. if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { if (data.hasExtra("returnKey1")) { Toast.makeText(this, data.getExtras().getString("returnKey1"), Toast.LENGTH_SHORT).show(); } } } Defining intent filters Intent filter Intents are used to signal to the Android system that a certain event has occurred. Intents often describe the action which should be performed and provide data upon which such an action should be done. For example, your application can start a browser component for a certain URL via an intent. This is demonstrated by the following example. String url = "http://www.exercise.com"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); But how does the Android system identify the components which can react to a certain intent? A component can register itself via an intent f ilter for a specific action and specific data. An intent filter specifies the types of intents to which an activity, service, or broadcast receiver can respond to by declaring the capabilities of a component.
  • 39. Android components register intent filters either statically in the AndroidManifest.xml or in case of a broadcast receiver also dynamically via code. An intent filter is defined by its category, action and data filters. It can also contain additional meta-data. If an intent is sent to the Android system, the Android platform runs a receiver determination. It uses the data included in the intent. If several components have registered for the same intent filter, the user can decide which component should be started. Defining intent filter You can register your Android components via intent filters for certain events. If a component does not define one, it can only be called by explicit intents. This chapter gives an example for registering a component for an intent. The key for this registration is that your component registers for the correct action, mime-type and specifies the correct meta-data. If you send such an intent to your system, the Android system determines all registered Android components for this intent. If several components have registered for this intent, the user can select which one should be used. Exercise: Key points to study: Description about Intent. Types of Intents. Develop an application which demonstrate the efficient use of explicit and implicit intents Ans- There are two types of intents in android 1. Implicit Intent 2. Explicit Intent
  • 40. Implicit Intent Using implicit Intent, components can’t be specified. An action to be performed is declared by implicit intent. Then android operating system will filter out components that will respond to the action. no component is specified, instead, an action is performed i.e. a webpage is going to be opened. As you type the name of your desired webpage and click on the ‘CLICK’ button. Your webpage is opened. File: activity_main.xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btn" android:text="Search" android:onClick="search" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/editText" /> </androidx.constraintlayout.widget.ConstraintLayout>
  • 41. File: MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { EditText editText; Button button; super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.btn); editText = (EditText) findViewById(R.id.editText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url=editText.getText().toString(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } }); } } Explicit Intent Using explicit intent any other component can be specified. In other words, the targeted component is specified by explicit intent. So only the specified target component will be invoked. For Example:
  • 42. In the above example, There are two activities (FirstActivity, and SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ button in the first activity, then you move to the second activity. When you click on the ‘GO TO HOME ACTIVITY’ button in the second activity, then you move to the first activity. This is getting done through Explicit Intent.
  • 43. 1. Introduction to android operating system and study of basic widgets. A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your home screen in order to quickly access them. You have probably seen some common widgets, such as music widget, weather widget, clock widget e.t.c Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets. Widget - XML file In order to create an application widget, first thing you need is AppWidgetProviderInfo object, which you will define in a separate widget XML file. In order to do that, right click on your project and create a new folder called xml. Now right click on the newly created folder and create a new XML file. The resource type of the XML file should be set to AppWidgetProvider. In the xml file, define some properties which are as follows – <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="146dp" android:updatePeriodMillis="0" android:minHeight="146dp" android:initialLayout="@layout/activity_main"> </appwidget-provider> Widget - Layout file Now you have to define the layout of your widget in your default XML file. You can drag components to generate auto xml. Widget - Java file After defining layout, now create a new JAVA file or use existing one, and extend it with AppWidgetProvider class and override its update method as follows.
  • 44. In the update method, you have to define the object of two classes which are PendingIntent and RemoteViews. Its syntax is − PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main); In the end you have to call an update method updateAppWidget() of the AppWidgetManager class. Its syntax is − appWidgetManager.updateAppWidget(currentWidgetId,views); A part from the updateAppWidget method, there are other methods defined in this class to manipulate widgets. They are as follows – Sr.No Method & Description 1 onDeleted(Context context, int[] appWidgetIds) This is called when an instance of AppWidgetProvider is deleted. 2 onDisabled(Context context) This is called when the last instance of AppWidgetProvider is deleted 3 onEnabled(Context context) This is called when an instance of AppWidgetProvider is created. 4 onReceive(Context context, Intent intent) It is used to dispatch calls to the various methods of the class Widget - Manifest file You also have to declare the AppWidgetProvider class in your manifest file as follows: <receiver android:name="ExampleAppWidgetProvider" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/example_appwidget_info" />
  • 45. </receiver> 2. Study of android lifecycle and demonstration of it. In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new activity starts, the previous one always remains below it. There are four stages of an activity. 1. If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running. This is usually the activity that the user is currently interacting with. 2. If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In such a case either another activity has a higher position in multi-window mode or the activity itself is not focusable in the current window mode. Such activity is completely alive. 3. If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information, and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere. 4. The system can destroy the activity from memory by either asking it to finish or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. For each stage, android provides us with a set of 7 methods that have their own significance for each stage in the life cycle. The image shows a path of migration whenever an app switches from one state to another.
  • 46. Demo Android App to Demonstrate Activity Lifecycle in Android File: MainActivity.java 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); Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show(); } protected void onStart() { super.onStart(); Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show(); }
  • 47. @Override protected void onRestart() { super.onRestart(); Toast toast = Toast.makeText(getApplicationContext(), "onRestart Called", Toast.LENGTH_LONG).show(); } protected void onPause() { super.onPause(); Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show(); } protected void onResume() { super.onResume(); Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show(); } protected void onStop() { super.onStop(); Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show(); } protected void onDestroy() { super.onDestroy(); Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show(); } }
  • 48. 3. Study of Different Layouts Android Layout is used to define the user interface that holds the UI controls or widgets that will appear on the screen of an android application or activity screen. Generally, every application is a combination of View and ViewGroup. As we know, an android application contains a large number of activities and we can say each activity is one page of the application. So, each activity contains multiple user interface components and those components are the instances of the View and ViewGroup. All the elements in a layout are built using a hierarchy of View and ViewGroup objects. View: A View is defined as the user interface which is used to create interactive UI components such as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and drawing. They are Generally Called Widgets. View: A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and to define the layout properties. They are Generally Called layouts.
  • 49. ViewGroup : The Android framework will allow us to use UI elements or widgets in two ways: 1. Use UI elements in the XML file 2. Create elements in the Kotlin file dynamically Types of Android Layout  Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property.  Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of the parent).  Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position of layout constraints for every child View relative to other views present. A ConstraintLayout is similar to a RelativeLayout, but having more power.  Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View elements it contains on the top of each other to display only a single View inside the FrameLayout.  Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View elements in rows and columns.  Android Web View: WebView is a browser that is used to display the web pages in our activity layout.  Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single column.  Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items in a grid view of rows and columns.
  • 50. 4. To build Calculator App using Linear Layouts The complete interface code of 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:paddingLeft="@dimen/activity_horizontal_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:textStyle="bold|italic" android:fontFamily="serif" android:visibility="visible" android:textSize="24sp" android:layout_weight="0.07" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:ems="10" android:id="@+id/editOp1" android:textSize="18sp" android:gravity="center_horizontal"
  • 51. 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:text="-" 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" />
  • 52. <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:text="@string/result" 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>
  • 53. So now we have designed the complete UI of the Calculator App. File: MainActivity.java package abhiandroid.com.calculater; 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 opr1; private EditText opr2; private Button btnadd; private Button btnsub; private Button btnmul; private Button btndiv; private Button btnclr; private TextView txtresult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); opr1 = (EditText) findViewById(R.id.editOp1); opr2 = (EditText) findViewById(R.id.editOp2);
  • 54. btnadd = (Button) findViewById(R.id.btnadd); btnsub = (Button) findViewById(R.id.btnsub); btnmul = (Button) findViewById(R.id.btnmul); btndiv = (Button) findViewById(R.id.btndiv); btnclr = (Button) findViewById(R.id.btnclr); txtresult= (TextView) findViewById(R.id.result); // Addition btnadd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if((opr1.getText().length()>0) && (opr2.getText().length()>0)) { double oper1 = Double.parseDouble(opr1.getText().toString()); double oper2 = Double.parseDouble(opr2.getText().toString()); double result = oper1 + oper2; txtresult.setText(Double.toString(result)); } else{ Toast toast= Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_LONG); toast.show(); } } }); //Subtraction btnsub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if((opr1.getText().length()>0) && (opr2.getText().length()>0)) { double oper1 = Double.parseDouble(opr1.getText().toString()); double oper2 = Double.parseDouble(opr2.getText().toString()); double result = oper1 - oper2; txtresult.setText(Double.toString(result)); } else{ Toast toast= Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_LONG); toast.show(); } } }); // Multiplication
  • 55. btnmul.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if((opr1.getText().length()>0) && (opr2.getText().length()>0)) { double oper1 = Double.parseDouble(opr1.getText().toString()); double oper2 = Double.parseDouble(opr2.getText().toString()); double result = oper1 * oper2; txtresult.setText(Double.toString(result)); } else{ Toast toast= Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_LONG); toast.show(); } } }); // Division btndiv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if((opr1.getText().length()>0) && (opr2.getText().length()>0)) { double oper1 = Double.parseDouble(opr1.getText().toString()); double oper2 = Double.parseDouble(opr2.getText().toString()); double result = oper1 / oper2; txtresult.setText(Double.toString(result)); } else{ Toast toast= Toast.makeText(MainActivity.this,"Enter The Required Numbers",Toast.LENGTH_LONG); toast.show(); } } }); // Reset Feilds btnclr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { opr1.setText(""); opr2.setText(""); txtresult.setText("0.00"); opr1.requestFocus(); }
  • 56. }); } } 5. To Build Login App using different Layouts MainActivity.java.
  • 57. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.graphics.Color; 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 Activity { Button b1,b2; EditText ed1,ed2; TextView tx1; int counter = 3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button)findViewById(R.id.button); ed1 = (EditText)findViewById(R.id.editText); ed2 = (EditText)findViewById(R.id.editText2); b2 = (Button)findViewById(R.id.button2); tx1 = (TextView)findViewById(R.id.textView3); tx1.setVisibility(View.GONE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(ed1.getText().toString().equals("admin") && ed2.getText().toString().equals("admin")) { Toast.makeText(getApplicationContext(), "Redirecting...",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(), "Wrong Credentials",Toast.LENGTH_SHORT).show(); tx1.setVisibility(View.VISIBLE); tx1.setBackgroundColor(Color.RED); counter--; tx1.setText(Integer.toString(counter));
  • 58. if (counter == 0) { b1.setEnabled(false); } } } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } 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" android:paddingLeft= "@dimen/activity_horizontal_margin" android:paddingRight = "@dimen/activity_horizontal_margin" android:paddingTop = "@dimen/activity_vertical_margin" android:paddingBottom = "@dimen/activity_vertical_margin" tools:context = ".MainActivity"> <TextView android:text = "Login" android:layout_width="wrap_content" android:layout_height = "wrap_content" android:id = "@+id/textview" android:textSize = "35dp" android:layout_alignParentTop = "true" android:layout_centerHorizontal = "true" /> <TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Tutorials point" android:id = "@+id/textView" android:layout_below = "@+id/textview" android:layout_centerHorizontal = "true" android:textColor = "#ff7aff24" android:textSize = "35dp" /> <EditText android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:id = "@+id/editText"
  • 59. android:hint = "Enter Name" android:focusable = "true" android:textColorHighlight = "#ff7eff15" android:textColorHint = "#ffff25e6" android:layout_marginTop = "46dp" android:layout_below = "@+id/imageView" android:layout_alignParentLeft = "true" android:layout_alignParentStart = "true" android:layout_alignParentRight = "true" android:layout_alignParentEnd = "true" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/editText2" android:layout_below="@+id/editText" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignRight="@+id/editText" android:layout_alignEnd="@+id/editText" android:textColorHint="#ffff299f" android:hint="Password" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Attempts Left:" android:id="@+id/textView2" android:layout_below="@+id/editText2" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:textSize="25dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/textView3"
  • 60. android:layout_alignTop="@+id/textView2" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignBottom="@+id/textView2" android:layout_toEndOf="@+id/textview" android:textSize="25dp" android:layout_toRightOf="@+id/textview" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="login" android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_toLeftOf="@+id/textview" android:layout_toStartOf="@+id/textview" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel" android:id="@+id/button2" android:layout_alignParentBottom="true" android:layout_toRightOf="@+id/textview" android:layout_toEndOf="@+id/textview" /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name="app_name">My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" >
  • 61. <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> 6. To Build a Stopwatch Application
  • 62. 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" <!-- Add some background color --> android:background="#0F9D58" android:padding="16dp" tools:context="org.geeksforgeeks.stopwatch.StopwatchActivity"> <TextView <!-- We will use text view "time_view" --> <!-- to display the number of seconds. --> android:id="@+id/time_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" <!-- These below attributes make the stopwatch --> <!-- timer nice and big. --> android:textAppearance="@android:style/TextAppearance.Large" android:textSize="56sp" /> <Button <!-- This code is for the Start button. android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" <!-- When it gets clicked, the Start button --> <!-- calls the onClickStart() method. --> android:onClick="onClickStart" android:text="@string/start" /> <Button
  • 63. <!-- This code is for the Stop button. --> android:id="@+id/stop_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" <!-- When it gets clicked, the Stop button --> <!-- calls the onClickStop() method. --> android:onClick="onClickStop" android:text="@string/stop" /> <Button <!-- This code is for Reset button. --> android:id="@+id/reset_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="8dp" <!-- When it gets clicked, the Reset button --> <!-- calls the onClickReset() method. --> android:onClick="onClickReset" android:text="@string/reset" /> </LinearLayout> MainActivity.java. package org.geeksforgeeks.stopwatch; import android.app.Activity; import android.os.Handler; import android.view.View; import android.os.Bundle; import java.util.Locale; import android.widget.TextView; public class StopwatchActivity extends Activity { // Use seconds, running and wasRunning respectively // to record the number of seconds passed, // whether the stopwatch is running and // whether the stopwatch was running
  • 64. // before the activity was paused. // Number of seconds displayed // on the stopwatch. private int seconds = 0; // Is the stopwatch running? private boolean running; private boolean wasRunning; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stopwatch); if (savedInstanceState != null) { // Get the previous state of the stopwatch // if the activity has been // destroyed and recreated. seconds = savedInstanceState .getInt("seconds"); running = savedInstanceState .getBoolean("running"); wasRunning = savedInstanceState .getBoolean("wasRunning"); } runTimer(); } // Save the state of the stopwatch // if it's about to be destroyed. @Override public void onSaveInstanceState( Bundle savedInstanceState) { savedInstanceState .putInt("seconds", seconds); savedInstanceState .putBoolean("running", running);
  • 65. savedInstanceState .putBoolean("wasRunning", wasRunning); } // If the activity is paused, // stop the stopwatch. @Override protected void onPause() { super.onPause(); wasRunning = running; running = false; } // If the activity is resumed, // start the stopwatch // again if it was running previously. @Override protected void onResume() { super.onResume(); if (wasRunning) { running = true; } } // Start the stopwatch running // when the Start button is clicked. // Below method gets called // when the Start button is clicked. public void onClickStart(View view) { running = true; } // Stop the stopwatch running // when the Stop button is clicked. // Below method gets called // when the Stop button is clicked. public void onClickStop(View view) { running = false; }
  • 66. // Reset the stopwatch when // the Reset button is clicked. // Below method gets called // when the Reset button is clicked. public void onClickReset(View view) { running = false; seconds = 0; } // Sets the NUmber of seconds on the timer. // The runTimer() method uses a Handler // to increment the seconds and // update the text view. private void runTimer() { // Get the text view. final TextView timeView = (TextView)findViewById( R.id.time_view); // Creates a new Handler final Handler handler = new Handler(); // Call the post() method, // passing in a new Runnable. // The post() method processes // code without a delay, // so the code in the Runnable // will run almost immediately. handler.post(new Runnable() { @Override public void run() { int hours = seconds / 3600; int minutes = (seconds % 3600) / 60; int secs = seconds % 60; // Format the seconds into hours, minutes, // and seconds. String time
  • 67. = String .format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, secs); // Set the text view text. timeView.setText(time); // If running is true, increment the // seconds variable. if (running) { seconds++; } // Post the code again // with a delay of 1 second. handler.postDelayed(this, 1000); } }); } }
  • 68. 7. To Build a Business Visiting Card <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="76dp" android:scaleType="centerCrop" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.497" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/jalogo" /> <TextView android:id="@+id/nameField" style="@style/TextAppearance.AppCompat.Headline" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="JANE APPLESEED" android:textColor="@color/colorPrimaryDark" android:textSize="25sp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <TextView android:id="@+id/titleField" style="@style/TextAppearance.AppCompat.Widget.ActionBar.Subtitle" android:layout_width="wrap_content" android:layout_height="wrap_content"
  • 69. android:layout_marginTop="13dp" android:text="Educator" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/nameField" /> <View android:id="@+id/horizontalLine" android:layout_width="300dp" android:layout_height="2dp" android:layout_marginTop="96dp" android:background="@color/colorPrimaryDark" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.495" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/titleField" /> <TextView android:id="@+id/phoneField" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="+123 4567890" android:textSize="15sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/horizontalLine" /> <TextView android:id="@+id/emailField" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:text="janeappleseed@gmail.com" android:textSize="15sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.485" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/phoneField" /> <TextView android:id="@+id/locationField" android:layout_width="wrap_content" android:layout_height="wrap_content"
  • 70. android:layout_marginTop="16dp" android:text="California, USA" android:textSize="15sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.492" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/emailField" /> <TextView android:id="@+id/websiteField" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="32dp" android:text="janeappleseed.com" android:textColor="@color/colorPrimaryDark" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/locationField" app:layout_constraintVertical_bias="1.0" /> <?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#009688</color> <color name="colorPrimaryDark">#00675b</color> <color name="colorPrimaryLight">#52c7b8</color> <color name="colorAccent">#03DAC5</color> </resources>
  • 71. 8. To Study and Build Applications using Intents Android uses Intent for communicating between the components of an Application and also from one application to another application. Intent are the objects which is used in android for passing the information among Activities in an Application and from one app to another also. Intent are used for communicating between the Application components and it also provides the connectivity between two apps. Types of Intents: Intent are of two types: Explicit Intent and Implicit Intent Explicit Intent: Explicit Intents are used to connect the application internally. In Explicit we use the name of component which will be affected by Intent. For Example: If we know class name then we can navigate the app from One Activity to another activity using Intent. In the similar way we can start a service to download a file in background process. Implicit Intent: In Implicit Intents we do need to specify the name of the component. We just specify the Action which has to be performed and further this action is handled by the component of another application. The basic example of implicit Intent is to open any web page Intent Example In Android: The example will show you both implicit and explicit Intent together. activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  • 72. xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="If you click on Explicit example we will navigate to second activity within App and if you click on Implicit example AbhiAndroid Homepage will open in Browser" android:id="@+id/textView2" android:clickable="false" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:layout_marginTop="42dp" android:background="#3e7d02" android:textColor="#ffffff" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Explicit Intent Example" android:id="@+id/explicit_Intent" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="147dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Implicit Intent Example" android:id="@+id/implicit_Intent" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout> Step 2: Design the UI of second activity activity_second.xml Now lets design UI of another activity where user will navigate after he click on Explicit Example button. Go to layout folder, create a new activity and name it activity_second.xml.
  • 73.  In this activity we will simply use TextView to tell user he is now on second activity. Below is the complete code of activity_second.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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:background="#CCEEAA" tools:context="com.example.android.intents.SecondActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="This is Second Activity" android:id="@+id/textView" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout> Step 3: Implement onClick event for Implicit And Explicit Button inside MainActivity.java Now we will use setOnClickListener() method to implement OnClick event on both the button. Implicit button will open AbhiAndroid.com homepage in browser and Explicit button will move to SecondActivity.java. Below is the complete code of MainActivity.java package com.example.android.intents; 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; public class MainActivity extends AppCompatActivity { Button explicit_btn, implicit_btn;
  • 74. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); explicit_btn = (Button)findViewById(R.id.explicit_Intent); implicit_btn = (Button) findViewById(R.id.implicit_Intent); //implement Onclick event for Explicit Intent explicit_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getBaseContext(), SecondActivity.class); startActivity(intent); } }); //implement onClick event for Implicit Intent implicit_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("https://www.abhiandroid.com")); startActivity(intent); } }); } } Step 4: Create A New JAVA class name SecondActivity Now we need to create another SecondActivity.java which will simply open the layout of activity_second.xml . Also we will use Toast to display message that he is on second activity. Below is the complete code of SecondActivity.java: package com.example.android.intents; import android.support.v7.app.AppCompatActivity;
  • 75. import android.os.Bundle; import android.widget.Toast; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Toast.makeText(getApplicationContext(), "We are moved to second Activity",Toast.LENGTH_LONG).show(); } } 9. To Build Quiz App activity_main.xml <?xml version="1.0" encoding="utf-8"?> <!--Using linear layout with vertical orientation and center gravity --> <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:background="#FFFFFF" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <!--ImageView used for showing pictures along with questions--> <ImageView android:id="@+id/myimage" android:layout_width="wrap_content" android:src="@drawable/f1" android:layout_height="wrap_content"/> <!--TextView used for showing questions on screen--> <TextView android:id="@+id/answer_text_view" android:text="@string/a" android:textColor="@android:color/black" android:textSize="30sp" android:padding="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  • 76. <!--Using another LinearLayout for showing buttons in horizontal orientation--> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <!--TrueButton--> <Button android:id="@+id/true_button" android:layout_marginRight="20dp" android:backgroundTint="#5BD91B" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:text="@string/true_text" /> <!--FalseButton--> <Button android:id="@+id/false_button" android:layout_marginLeft="20dp" android:layout_width="wrap_content" android:backgroundTint="#E33328" android:layout_height="wrap_content" android:textSize="20sp" android:text="@string/false_text" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <!--PreviousButton--> <ImageButton android:id="@+id/prev_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/baseline_keyboard_arrow_left_black_18dp" android:backgroundTint="#DFD2D1" android:text="@string/prev_text" /> <!--NextButton--> <ImageButton android:id="@+id/next_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="#DFD2D1" android:src="@drawable/baseline_keyboard_arrow_right_black_18dp" android:text="@string/next_text" /> </LinearLayout> </LinearLayout>
  • 77. MainActivity.java package org.geeksforgeeks.quizapp; import android.annotation.SuppressLint; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { // setting up things private Button falseButton; private Button trueButton; private ImageButton nextButton; private ImageButton prevButton; private ImageView Image; private TextView questionTextView; private int correct = 0; // to keep current question track private int currentQuestionIndex = 0; private Question[] questionBank = new Question[] { // array of objects of class Question // providing questions from string // resource and the correct ans new Question(R.string.a, true), new Question(R.string.b, false), new Question(R.string.c, true), new Question(R.string.d, true), new Question(R.string.e, true), new Question(R.string.f, false), }; @Override
  • 78. protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // setting up the buttons // associated with id falseButton = findViewById(R.id.false_button); trueButton = findViewById(R.id.true_button); nextButton = findViewById(R.id.next_button); prevButton = findViewById(R.id.prev_button); // register our buttons to listen to // click events questionTextView = findViewById(R.id.answer_text_view); Image = findViewById(R.id.myimage); falseButton.setOnClickListener(this); trueButton.setOnClickListener(this); nextButton.setOnClickListener(this); prevButton.setOnClickListener(this); } @SuppressLint("SetTextI18n") @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public void onClick(View v) { // checking which button is // clicked by user // in this case user choose false switch (v.getId()) { case R.id.false_button: checkAnswer(false); break; case R.id.true_button: checkAnswer(true); break; case R.id.next_button: // go to next question // limiting question bank range if (currentQuestionIndex < 7) { currentQuestionIndex = currentQuestionIndex + 1;
  • 79. // we are safe now! // last question reached // making buttons // invisible if (currentQuestionIndex == 6) { questionTextView.setText(getString( R.string.correct, correct)); nextButton.setVisibility( View.INVISIBLE); prevButton.setVisibility( View.INVISIBLE); trueButton.setVisibility( View.INVISIBLE); falseButton.setVisibility( View.INVISIBLE); if (correct > 3) questionTextView.setText( "CORRECTNESS IS " + correct + " " + "OUT OF 6"); // showing correctness else Image.setImageResource( R.drawable.resu); // if correctness<3 showing sad emoji } else { updateQuestion(); } } break; case R.id.prev_button: if (currentQuestionIndex > 0) { currentQuestionIndex = (currentQuestionIndex - 1) % questionBank.length; updateQuestion(); } } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  • 80. private void updateQuestion() { Log.d("Current", "onClick: " + currentQuestionIndex); questionTextView.setText( questionBank[currentQuestionIndex] .getAnswerResId()); // setting the textview with new question switch (currentQuestionIndex) { case 1: // setting up image for each // question Image.setImageResource(R.drawable.f2); break; case 2: Image.setImageResource(R.drawable.f3); break; case 3: Image.setImageResource(R.drawable.f4); break; case 4: Image.setImageResource(R.drawable.f5); break; case 5: Image.setImageResource(R.drawable.f6); break; case 6: Image.setImageResource(R.drawable.f7); break; case 7: Image.setImageResource(R.drawable.f1); break; } } private void checkAnswer(boolean userChooseCorrect) { boolean answerIsTrue = questionBank[currentQuestionIndex] .isAnswerTrue(); // getting correct ans of current question int toastMessageId; // if ans matches with the // button clicked
  • 81. if (userChooseCorrect == answerIsTrue) { toastMessageId = R.string.correct_answer; correct++; } else { // showing toast // message correct toastMessageId = R.string.wrong_answer; } Toast .makeText(MainActivity.this, toastMessageId, Toast.LENGTH_SHORT) .show(); } } 10.To Build Tic Tac Toe Game activity_main.xml file <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:background="@color/green" tools:context=".MainActivity"> <!--title text--> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="23dp" android:text="GFG Tic Tac Toe" android:textSize="45sp" android:textStyle="bold" app:fontFamily="cursive" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />
  • 82. <!--image of the grid--> <ImageView android:id="@+id/imageView" android:layout_width="0dp" android:layout_height="wrap_content" android:contentDescription="Start" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:srcCompat="@drawable/grid" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="0dp" android:layout_height="420dp" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="@+id/imageView" app:layout_constraintEnd_toEndOf="@+id/imageView" app:layout_constraintStart_toStartOf="@+id/imageView" app:layout_constraintTop_toTopOf="@+id/imageView"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <!--images of the grid boxes--> <ImageView android:id="@+id/imageView0" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="0" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="1" /> <ImageView android:id="@+id/imageView2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"
  • 83. android:onClick="playerTap" android:padding="20sp" android:tag="2" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <ImageView android:id="@+id/imageView3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="3" /> <ImageView android:id="@+id/imageView4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="4" /> <ImageView android:id="@+id/imageView5" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="5" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <ImageView android:id="@+id/imageView6" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp"
  • 84. android:tag="6" /> <ImageView android:id="@+id/imageView7" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="7" /> <ImageView android:id="@+id/imageView8" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="playerTap" android:padding="20sp" android:tag="8" /> </LinearLayout> </LinearLayout> <!--game status text display--> <TextView android:id="@+id/status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="15sp" android:text="Status" android:textSize="28sp" android:textStyle="italic" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout" /> </androidx.constraintlayout.widget.ConstraintLayout> MainActivity.java import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity {
  • 85. boolean gameActive = true; // Player representation // 0 - X // 1 - O int activePlayer = 0; int[] gameState = {2, 2, 2, 2, 2, 2, 2, 2, 2}; // State meanings: // 0 - X // 1 - O // 2 - Null // put all win positions in a 2D array int[][] winPositions = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; public static int counter = 0; // this function will be called every time a // players tap in an empty box of the grid public void playerTap(View view) { ImageView img = (ImageView) view; int tappedImage = Integer.parseInt(img.getTag().toString()); // game reset function will be called // if someone wins or the boxes are full if (!gameActive) { gameReset(view); } // if the tapped image is empty if (gameState[tappedImage] == 2) { // increase the counter // after every tap counter++; // check if its the last box if (counter == 9) { // reset the game gameActive = false; }