Subject - Android
Semester - 5 BCA
Table Of Content
(Click to View)
Experiment- 1
Aim: Create a Program of Activity Lifecycle?
Description: It shows the actual features of Android activity lifecycle goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() .
Steps:
1. onCreate():
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);
// Bundle containing previous frozen state
setContentView(R.layout.activity_main);
// The content view pointing to the id of layout
// in the file activity_main.xml
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}
}
2. onStart():
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);
// Bundle containing previous frozen state
setContentView(R.layout.activity_main);
// The content view pointing to the id of layout
// in the file activity_main.xml
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}
protected void onStart()
{
// It will show a message on the screen
// then onStart is invoked
Toast toast = Toast.makeText(getApplicationContext(), "onStart Called", Toast.LENGTH_LONG).show();
}
}
3. onResume():
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.example.share.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// Bundle containing previous frozen state
super.onCreate(savedInstanceState);
// The content view pointing to the id of layout
// in the file activity_main.xml
setContentView(R.layout.activity_main);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}
protected void onResume() {
// It will show a message on the screen
// then onResume is invoked
Toast toast = Toast.makeText(getApplicationContext(), "onResume Called", Toast.LENGTH_LONG).show();
}
}
4. onPause():
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) {
// Bundle containing previous frozen state
super.onCreate(savedInstanceState);
// The content view pointing to the id of layout
// in the file activity_main.xml
setContentView(R.layout.activity_main);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}
protected void onPause() {
// It will show a message on the screen
// then onPause is invoked
Toast toast = Toast.makeText(getApplicationContext(), "onPause Called", Toast.LENGTH_LONG).show();
}
}
5. onStop():
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) {
// Bundle containing previous frozen state
super.onCreate(savedInstanceState);
// The content view pointing to the id of layout
// in the file activity_main.xml
setContentView(R.layout.activity_main);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}
protected void onStop() {
// It will show a message on the screen
// then onStop is invoked
Toast toast = Toast.makeText(getApplicationContext(), "onStop Called", Toast.LENGTH_LONG).show();
}
}
6. onDestroy():
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) {
// Bundle containing previous frozen state
super.onCreate(savedInstanceState);
// The content view pointing to the id of layout
// in the file activity_main.xml
setContentView(R.layout.activity_main);
Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called", Toast.LENGTH_LONG).show();
}
protected void onDestroy() {
// It will show a message on the screen
// then onDestroy is invoked
Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called", Toast.LENGTH_LONG).show();
}
}
Post Practical Questions:
1. Android system initiates its program within an Activity starting with a call on ? ➡️ C
a) offCreate() callback
b) onDrop() callback
c) onCreate() callback
2.Which callback is called when the activity becomes visible to the user? ➡️ B
a) onCreate()
b) onStart()
c) onResume()
3. Which callback is called when the activity is no longer visible? ➡️ B
a) onRestart()
b) onStop()
c) onPause()
4. Which callback is called when the activity restarts after stopping it? ➡️ A
a) onRestart()
b) onPause()
c) onStart()
EXPERIMENT: 2
Aim: Create a program in Context and show different color and size of text?
Description: In the below program you will see that we have created a textView dynamically and passed context. This context is used to get the information about the environment.
Steps:
This example demonstrates how do I change font color of TextView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"tools:context=".MainActivity">
<TextViewandroid:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My color is Blue"
android:layout_centerInParent="true"
android:textStyle="bold"
android:textSize="36sp"/>
<TextViewandroid:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView1"
android:layout_marginBottom="10dp"
android:text="My color is Green"
android:textStyle="bold"
android:layout_centerInParent="true"
android:textSize="36sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class
MainActivity extends
AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);TextView textView1 = findViewById(R.id.textView1);
textView1.setTextColor(Color.BLUE);TextView textView2 = findViewById(R.id.textView2);
textView2.setTextColor(Color.parseColor("#006400"));}}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This example demonstrates how do I change the font size of TextView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextViewandroid:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Im Huge"
android:fontFamily="sans-serif-smallcaps"
android:layout_centerInParent="true"
android:textSize="64sp" />
<TextViewandroid:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView1"
android:layout_marginBottom="10dp"
android:text="Im small"
android:layout_centerInParent="true"
android:fontFamily="serif-monospace"
android:textSize="36sp" />
<TextViewandroid:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView2"
android:layout_marginBottom="10dp"
android:text="Im tiny"
android:layout_centerInParent="true"
android:fontFamily="serif-monospace"
android:textSize="24sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class
MainActivity extends
AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Post Practical Questions:
1. What is a context in android?
➡️ Context is used to create new components or objects like views and it is used to start activity and services.
2. The property that is used for formatting font is ➡️ B
a)Color
b) typeface
c) ImageView
3. What is the default font size in Android? ➡️ B
a) 12sp
b) 14sp
c) 16sp
EXPERIMENT : 3
Aim: Create option menu and shows in notify in toast?
Description: Android Option Menus are the primary menus of android. They can be used for settings, search, delete item etc. Here, you will inflating the menu by calling the inflate() method of Menu Inflater class. To perform event handling on menu items, you need to override onOptionsItemSelected() method of Activity class.
Steps:
Android Option Menu Example:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.optionmenu.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
File: context_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="example.javatpoint.com.optionmenu.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
File: menu_main.xml
<menu 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"
tools:context="example.javatpoint.com.optionmenu.MainActivity">
<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>
File: MainActivity.java
package example.javatpoint.com.optionmenu;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Post Practical Questions:
Q. 1 Explain Toast class and option menu?
➡️ Toast Class: Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction.
Toast Option Menu: Android Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime. The android. widget.
EXPERIMENT: 4
Aim: Create a program of animation with XML file?
Description: An animation defined in XML that modifies properties of the target object, such as background color or alpha value, over a set amount of time.
Steps:
Here is the modified code of res/layout/activity_main.xml.
Here abc indicates about logo of tutorials point
<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:text="Alert Dialog"
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="Tutorialspoint"
android:id="@+id/textView2"
android:textColor="#ff3eff0f"
android:textSize="35dp"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="zoom"android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:onClick="clockwise"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="clockwise"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
android:onClick="zoom"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fade"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"android:onClick="fade"/>
</RelativeLayout>
Here is the code of res/anim/myanimation.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
</set>
Here is the code of res/anim/clockwise.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
</set>
Here is the code of res/anim/fade.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator" >
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>
<alpha
android:startOffset="2000"
android:fromAlpha="1"
android:toAlpha="0"
android:duration="2000" >
</alpha>
</set>
Here is the modified code of res/values/string.xml.
<resources>
<string name="app_name">My Application</string>
</resources>
Here is the default code of AndroidManifest.xml.
<?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="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activityandroid:name="com.example.animation.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>
Post Practical Questions:
1. Explain XML Layout Attributes ?
➡️ Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout.
EXPERIMENT: 5
Aim: Create a program with button and chronometer?
Description: The Chronometer is a subclass of TextView. This class helps us to add a timer in our app. You can give Timer start time in the elapsedRealTime() timebase and it start counting from that. If we don’t give base time then it will use the time at which time we call start() method. By default a chronometer displays the current timer value in the form of MM:SS or H:MM:SS.
Steps:
Step by Step Implementation:
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the code below. Comments are added in the code to get to know in detail.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/idRLContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--on below line we are creating a simple text view-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/idCMmeter"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:gravity="center"
android:padding="10dp"
android:text="Chronometer in Android"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!--on below line we are creating a chronometer-->
<Chronometer
android:id="@+id/idCMmeter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:gravity="center"
android:padding="10dp"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!--on below line we are creating a
button to create a chronometer-->
<Button
android:id="@+id/idBtnChronometer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idCMmeter"
android:layout_margin="20dp"
android:padding="4dp"
android:text="Start Chronometer"
android:textAllCaps="false" />
</RelativeLayout>
Step 3: Working with the MainActivity file
Navigate to app > java > your app’s package name > Main Activity file and add the below code to it. Comments are added in the code to get to know in detail.
package com.gtappdevelopers.kotlingfgproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// on below line we are creating variables.
private Chronometer chronometer;
private Button chronometerBtn;
boolean isRunning = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// on below line we are initializing our variables.
chronometer = findViewById(R.id.idCMmeter);
chronometerBtn = findViewById(R.id.idBtnChronometer);
// on below line we are adding click listener for our button
chronometerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// on below line we are checking if
// chronometer is running or not.
if (isRunning) {
// in this condition chronometer is running
// on below line we are updating text for button
chronometerBtn.setText("Start Chronometer");
// on below line we are updating boolean variable
isRunning = false;
// on below line we are stopping chronometer
chronometer.stop();
} else {
// in this condition chronometer is running
// on below line we are updating text for button
chronometerBtn.setText("Stop Chronometer");
// on below line we are updating boolean variable
isRunning = true;
// on below line we are starting chronometer
chronometer.start();
}
}
});
}
}
Post Practical Questions:
1. Write it down the Android ChronoMeter Attributes ?
➡️ This attribute specifies a time format string for Chronometer. By default, Chronometer displays time in the format of "MM:SS" when the time is less than 1 hour, or "H:MM:SS" if the time is more than 1 hour.
EXPERIMENT: 6
Aim: Create a program of Grid View and shows multiple subjects names?
Description: Android Grid View shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not necessarily predetermined but they automatically inserted to the layout using a List Adapter.
Steps:
XML Attributes of GridView:
android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid.
android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView.
android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView.
Step By Step Implementation:
Step:1 Create a new Project in Android Studio:
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.
Step:2 Add the Required Dependencies :
Add the Google Repository to your settings.Gradle File.
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
// add the following
google()
mavenCentral()
}
}
Step:3 Working with the XML files :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- android:numColumns=2 is the number of columns for Grid View
android:horizontalSpacing is the space between horizontal grid items -->
<GridView
android:id="@+id/idGVcourses"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="6dp"
android:numColumns="2"
android:verticalSpacing="6dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Create an XML Layout for each item of GridView :
Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as card_item. Below is the code for the card_item.xml file.
<?xml version="1.0" encoding="utf-8"?><!-- XML implementation of Card Layout -->
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_gravity="center"
android:layout_margin="5dp"
app:cardCornerRadius="5dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/idIVcourse"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/idTVCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textAlignment="center" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Step:5 Create a Model Class for Storing Data :
Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java/Kotlin Class file as CourseModel. Below is the code for the <CourseModel file.
public class CourseModel {
// string course_name for storing course_name
// and imgid for storing image id.
private String course_name;
private int imgid;
public CourseModel(String course_name, int imgid) {
this.course_name = course_name;
this.imgid = imgid;
}
public String getCourse_name() {
return course_name;
}
public void setCourse_name(String course_name) {
this.course_name = course_name;
}
public int getImgid() {
return imgid;
}
public void setImgid(int imgid) {
this.imgid = imgid;
}
}
Step: 6 Create an Adapter Class :
Now click on app > java > apps package name > Right-Click on it. Then Click on New > Java Class. Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter file.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class CourseGVAdapter extends ArrayAdapter<CourseModel> {
public CourseGVAdapter(@NonNull Context context, ArrayList<CourseModel> courseModelArrayList) {
super(context, 0, courseModelArrayList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listitemView = convertView;
if (listitemView == null) {
// Layout Inflater inflates each item to be displayed in GridView.
listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false);
}
CourseModel courseModel = getItem(position);
TextView courseTV = listitemView.findViewById(R.id.idTVCourse);
ImageView courseIV = listitemView.findViewById(R.id.idIVcourse);
courseTV.setText(courseModel.getCourse_name());
courseIV.setImageResource(courseModel.getImgid());
return listitemView;
}
}
Step: 7 Working with the MainActivity File:
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.
import android.os.Bundle;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
GridView coursesGV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coursesGV = findViewById(R.id.idGVcourses);
ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>();
courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo));
courseModelArrayList.add(new CourseModel("JAVA", R.drawable.ic_gfglogo));
courseModelArrayList.add(new CourseModel("C++", R.drawable.ic_gfglogo));
courseModelArrayList.add(new CourseModel("Python", R.drawable.ic_gfglogo));
courseModelArrayList.add(new CourseModel("Javascript", R.drawable.ic_gfglogo));
courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo));
CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList);
coursesGV.setAdapter(adapter);
}
}
Post Practical Questions:
1. Explain Custom ArrayAdapter in GridView?
➡️ Android already provides the implementation for an ArrayAdapter, which can be used with just a single line demonstrated below. They are used when Whenever we have a list of single items we can use ArrayAdapter. For instance, a list of phone contacts, countries, or names.
The problem with or limitation of this method is we cannot use complex layouts eg. Imagine we were building an app like Netflix or prime where each element is made up of many elements eg an ImageView, TextView, etc. Such complex views are not possible with the simple implementation of the ArrayAdapter for this we need to create our custom Adapter by extending the ArrayAdapter class. The following code shows the structure of the Custom ArrayAdapter.
EXPERIMENT: 7
Aim: Create Simple Login Page with 3 attempt?
Description: Define a button with login text and set its onClick Property. After that define the function mentioned in the onClick property in the java file. In the java file, inside the method of onClick get the username and passwords text using getText() and toString() method and match it with the text using equals() function.
Steps:
Following is the content of the modified main activity file src/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() {
@Overridepublic 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();
}
});
}
}
Following is the modified content of the xml res/layout/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" />
<TextViewandroid: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" />
<EditTextandroid: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" />
<Buttonandroid: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" />
<Buttonandroid: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" >
<applicationandroid:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activityandroid: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>
Post Practical Questions:
1. How many orientations does android support? ➡️ D
a) 1
b) 2
c) 3
d) 4
2. How to get current location in android? ➡️ D
a) Using with GPRS
b) SQLite
c) Network servers
d) Location Provider
EXPERIMENT: 8
Aim: Create Simple Database Program with fatch data from SQLite Database with (name, phone, email, street, place)?
Steps:
Following is the content of the modified MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.item1:Bundle
dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayContact.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
Following is the modified content of display contact activity DisplayContact.java
package com.example.sairamkrishna.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed()) {
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
} else{
getMenuInflater().inflate(R.menu.menu_main menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(),
phone.getText().toString(), email.getText().toString(),
street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
} else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(),
email.getText().toString(), street.getText().toString(),
place.getText().toString())){
Toast.makeText(getApplicationContext(), "done",Toast.LENGTH_SHORT).show();} else{
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}
}
Following is the content of Database class DBHelper.java
package com.example.sairamkrishna.myapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
}
Following is the content of the res/layout/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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Data Base" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"/>
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/scrollView"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</ScrollView>
</RelativeLayout>
Following is the content of the res/layout/activity_display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".DisplayContact" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="370dp"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="82dp"
android:ems="10"
android:inputType="text" >
</EditText>
<EditText
android:id="@+id/editTextEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextStreet"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="textEmailAddress" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextName"
android:layout_alignParentLeft="true"
android:text="@string/name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="@string/save" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView1"
android:text="@string/email"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/editTextPhone"
android:layout_alignLeft="@+id/textView1"
android:text="@string/phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editTextEmail"
android:layout_alignLeft="@+id/textView5"
android:text="@string/street"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextCity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editTextName"
android:layout_below="@+id/editTextEmail"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editTextCity"
android:layout_alignBottom="@+id/editTextCity"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/editTextEmail"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editTextStreet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextName"
android:layout_below="@+id/editTextPhone"
android:ems="10"android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editTextStreet"
android:layout_below="@+id/editTextName"
android:ems="10"
android:inputType="phone|text" />
</RelativeLayout>
</ScrollView>
Following is the content of the res/value/string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Address Book</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="Add_New">Add New</string>
<string name="edit">Edit Contact</string>
<string name="delete">Delete Contact</string>
<string name="title_activity_display_contact">DisplayContact</string>
<string name="name">Name</string>
<string name="phone">Phone</string>
<string name="email">Email</string>
<string name="street">Street</string>
<string name="country">City/State/Zip</string>
<string name="save">Save Contact</string>
<string name="deleteContact">Are you sure, you want to delete it.</string>
<string name="yes">Yes</string>
<string name="no">No</string>
</resources>
Following is the content of the res/menu/main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/item1"
android:icon="@drawable/add"
android:title="@string/Add_New" >
</item>
</menu>
Following is the content of the res/menu/display_contact.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/Edit_Contact"
android:orderInCategory="100"
android:title="@string/edit"/>
<item
android:id="@+id/Delete_Contact"
android:orderInCategory="100"
android:title="@string/delete"/>
</menu>
This is the defualt AndroidManifest.xml of this project
<?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>
<activity android:name=".DisplayContact"/>
</application>
</manifest>
Post Practical Questions:
1. In SQLite, files are ____ directly to disk. ➡️ C
a) Read
b) Written
c) Both a and b
d) None of the above
2. SQLite is written in ➡️ B
a) C
b) ANSI-C
c) JAVA
d) None of these
3. SQLite is a ____ database resource. ➡️ D
a) Interface
b) Non-interface
c) Portable
d) Non-portable
EXPERIMENT: 9
Aim: Create an Implicit and Explicit intents Program?
Description: Types of Android Intents
There are two types of intents in android: implicit and explicit.
1) Implicit Intent:
Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);
2) Explicit Intent:
Explicit Intent specifies the component. In such case, intent provides the external class to be invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Steps:
Implicit Intent:
Creating an Android App to Open a Webpage Using Implicit Intent
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Create an XML file and Java File. Please refer to the pre-requisites to learn more about this step.
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Syntax:
android:id="@+id/id_name"
XML Code:
<?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>
Step 3: Working with the MainActivity File
Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
Syntax:
ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);
JAVA Code:
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
How to create an Android App to move to the next activity using Explicit Intent(with Example)
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with the activity_main.xml File
Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Syntax:
android:id="@+id/id_name"
XML Code:
<?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">
<TextView
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG Home Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn1"
android:text="Go to News Screen"
android:onClick="newsScreen"
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>
Step 3: Working with the MainActivity File
Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
Syntax:
ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);
Intent i = new Intent(getApplicationContext(), <className>);
startActivity(i);
JAVA Code:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void newsScreen(View view) {
Intent i = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(i);
}
}
Step 4: Working with the activity_main2.xml File
Now we have to create a second activity as a destination activity. The steps to create the second activity are File > new > Activity > Empty Activity.
Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for the activity_main2.xml file. Comments are added inside the code to understand the code in more detail.
XML Code:
<?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=".MainActivity2">
<TextView
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG News Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn2"
android:text="Go to Home Screen"
android:onClick="homeScreen"
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>
Step 5: Working with the MainActivity2 File
Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.
Syntax:
ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);
Intent i = new Intent(getApplicationContext(), <className>);
startActivity(i);
JAVA Code:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void homeScreen(View view) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
Post Practical Questions:
1. If you want to navigate from one activity to another then android provides you which class ➡️ C
a) startActivity
b) Object
c) Intent
d) Adapter
2.The types of intents in android is\are distinguishes data classes or concepts. ➡️ D
a) Explicit intents
b) Implicit intents
c) Start intents
d) Option A and B are correct.
3.Suppose that there are two activities in an application named ActivityOne and ActivityTwo. You want to invoke ActivityTwo from ActivityOne. What code you will write? ➡️ A
a) Intent intent=new Intent (this, ActivityTwo.class); startActivity(intent);
b) startActivity(new Intent(this, ActivityTwo.class));
c) Option A and B are correct.
d) None of the above.
EXPERIMENT : 10
Aim: Make a Scientific Calculator Android App using Android Studio using multiple buttons?
Steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding new colors to the colors.xml file
Navigate to the app > res > values > colors.xml file and add the below code to it for different colors. Comments are added in the code to get to know in more detail.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#0F9D58</color>
<color name="purple_500">#0F9D58</color>
<color name="purple_700">#0F9D58</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<!--three different shades of black color-->
<color name="blac_shade_1">#292D36</color>
<color name="black_shade_2">#272B33</color>
<color name="black_shade_3">#22252D</color>
<color name="yellow">#ffa500</color>
</resources>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black_shade_3"
tools:context=".MainActivity">
<TextView
android:id="@+id/idTVSecondary"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="@color/black_shade_3"
android:gravity="bottom"
android:maxLines="1"
android:padding="10dp"
android:paddingTop="30dp"
android:text=""
android:textAlignment="viewEnd"
android:textColor="@color/white"
android:textSize="15sp"
tools:ignore="RtlCompat" />
<TextView
android:id="@+id/idTVprimary"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="@id/idTVSecondary"
android:background="@color/black_shade_3"
android:gravity="bottom"
android:maxLines="1"
android:padding="10dp"
android:text=""
android:textAlignment="viewEnd"
android:textColor="#fff"
android:textSize="50sp"
tools:ignore="RtlCompat" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/idTVprimary"
android:background="@color/blac_shade_1"
app:cardCornerRadius="4dp"
app:cardElevation="2dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="7"
android:background="@color/blac_shade_1"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="7">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/bac"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="AC"
android:textColor="@color/yellow"
android:textSize="15sp"
tools:targetApi="lollipop" />
<Button
android:id="@+id/bc"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="C"
android:textColor="@color/yellow"
android:textSize="15sp" />
<Button
android:id="@+id/bbrac1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="("
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bbrac2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text=")"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="5">
<Button
android:id="@+id/bsin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="sin"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bcos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="cos"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/btan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="tan"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/blog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="log"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bln"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="ln"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="5">
<Button
android:id="@+id/bfact"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="x!"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bsquare"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="x²"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bsqrt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="√"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/binv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="1/x"
android:textAllCaps="false"
android:textColor="#ffa500"
android:textSize="15sp" />
<Button
android:id="@+id/bdiv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="÷"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/b7"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="7"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b8"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="8"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b9"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="9"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bmul"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="×"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/b4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="4"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b5"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="5"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="6"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bminus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="-"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="1"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="2"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="3"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bplus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="+"
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="4">
<Button
android:id="@+id/bpi"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="π"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/b0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="0"
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bdot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="."
android:textColor="#fff"
android:textSize="15sp" />
<Button
android:id="@+id/bequal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="3dp"
android:layout_weight="1"
android:backgroundTint="@color/black_shade_2"
android:padding="6dp"
android:text="="
android:textColor="#ffa500"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin Code:
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
// creating variables for our text view and button
lateinit var tvsec: TextView
lateinit var tvMain: TextView
lateinit var bac: Button
lateinit var bc: Button
lateinit var bbrac1: Button
lateinit var bbrac2: Button
lateinit var bsin: Button
lateinit var bcos: Button
lateinit var btan: Button
lateinit var blog: Button
lateinit var bln: Button
lateinit var bfact: Button
lateinit var bsquare: Button
lateinit var bsqrt: Button
lateinit var binv: Button
lateinit var b0: Button
lateinit var b9: Button
lateinit var b8: Button
lateinit var b7: Button
lateinit var b6: Button
lateinit var b5: Button
lateinit var b4: Button
lateinit var b3: Button
lateinit var b2: Button
lateinit var b1: Button
lateinit var bpi: Button
lateinit var bmul: Button
lateinit var bminus: Button
lateinit var bplus: Button
lateinit var bequal: Button
lateinit var bdot: Button
lateinit var bdiv: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initializing all our variables.
tvsec = findViewById(R.id.idTVSecondary)
tvMain = findViewById(R.id.idTVprimary)
bac = findViewById(R.id.bac)
bc = findViewById(R.id.bc)
bbrac1 = findViewById(R.id.bbrac1)
bbrac2 = findViewById(R.id.bbrac2)
bsin = findViewById(R.id.bsin)
bcos = findViewById(R.id.bcos)
btan = findViewById(R.id.btan)
blog = findViewById(R.id.blog)
bln = findViewById(R.id.bln)
bfact = findViewById(R.id.bfact)
bsquare = findViewById(R.id.bsquare)
bsqrt = findViewById(R.id.bsqrt)
binv = findViewById(R.id.binv)
b0 = findViewById(R.id.b0)
b9 = findViewById(R.id.b9)
b8 = findViewById(R.id.b8)
b7 = findViewById(R.id.b7)
b6 = findViewById(R.id.b6)
b5 = findViewById(R.id.b5)
b4 = findViewById(R.id.b4)
b3 = findViewById(R.id.b3)
b2 = findViewById(R.id.b2)
b1 = findViewById(R.id.b1)
bpi = findViewById(R.id.bpi)
bmul = findViewById(R.id.bmul)
bminus = findViewById(R.id.bminus)
bplus = findViewById(R.id.bplus)
bequal = findViewById(R.id.bequal)
bdot = findViewById(R.id.bdot)
bdiv = findViewById(R.id.bdiv)
// adding on click listener to our all buttons.
b1.setOnClickListener {
// on below line we are appending
// the expression to our text view.
tvMain.text = (tvMain.text.toString() + "1")
}
b2.setOnClickListener {
// on below line we are appending
// the expression to our text view.
tvMain.text = (tvMain.text.toString() + "2")
}
b3.setOnClickListener {
// on below line we are appending
// the expression to our text view.
tvMain.text = (tvMain.text.toString() + "3")
}
b4.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "4")
}
b5.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "5")
}
b6.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "6")
}
b7.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "7")
}
b8.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "8")
}
b9.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "9")
}
b0.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "0")
}
bdot.setOnClickListener {
tvMain.text = (tvMain.text.toString() + ".")
}
bplus.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "+")
}
bdiv.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "/")
}
bbrac1.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "(")
}
bbrac2.setOnClickListener {
tvMain.text = (tvMain.text.toString() + ")")
}
bpi.setOnClickListener {
// on clicking on pi button we are adding
// pi value as 3.142 to our current value.
tvMain.text = (tvMain.text.toString() + "3.142")
tvsec.text = (bpi.text.toString())
}
bsin.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "sin")
}
bcos.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "cos")
}
btan.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "tan")
}
binv.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "^" + "(-1)")
}
bln.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "ln")
}
blog.setOnClickListener {
tvMain.text = (tvMain.text.toString() + "log")
}
bminus.setOnClickListener {
// on clicking on minus we are checking if
// the user has already a minus operation on screen.
// if minus operation is already present
// then we will not do anything.
val str: String = tvMain.text.toString()
if (!str.get(index = str.length - 1).equals("-")) {
tvMain.text = (tvMain.text.toString() + "-")
}
}
bmul.setOnClickListener {
// if mul sign is not present in our
// text view then only we are adding
// the multiplication operator to it.
val str: String = tvMain.text.toString()
if (!str.get(index = str.length - 1).equals("*")) {
tvMain.text = (tvMain.text.toString() + "*")
}
}
bsqrt.setOnClickListener {
if (tvMain.text.toString().isEmpty()) {
// if the entered number is empty we are displaying an error message.
Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show()
} else {
val str: String = tvMain.text.toString()
// on below line we are calculation
// square root of the given number.
val r = Math.sqrt(str.toDouble())
// on below line we are converting our double
// to string and then setting it to text view.
val result = r.toString()
tvMain.setText(result)
}
}
bequal.setOnClickListener {
val str: String = tvMain.text.toString()
// on below line we are calling an evaluate
// method to calculate the value of expressions.
val result: Double = evaluate(str)
// on below line we are getting result
// and setting it to text view.
val r = result.toString()
tvMain.setText(r)
tvsec.text = str
}
bac.setOnClickListener {
// on clicking on ac button we are clearing
// our primary and secondary text view.
tvMain.setText("")
tvsec.setText("")
}
bc.setOnClickListener {
// on clicking on c button we are clearing
// the last character by checking the length.
var str: String = tvMain.text.toString()
if (!str.equals("")) {
str = str.substring(0, str.length - 1)
tvMain.text = str
}
}
bsquare.setOnClickListener {
if (tvMain.text.toString().isEmpty()) {
// if the entered number is empty we are displaying an error message.
Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show()
} else {
// on below line we are getting the expression and then calculating the square of the number
val d: Double = tvMain.getText().toString().toDouble()
// on below line we are calculating the square.
val square = d * d
// after calculating the square we
// are setting it to text view.
tvMain.setText(square.toString())
// on below line we are setting
// the d to secondary text view.
tvsec.text = "$d²"
}
}
bfact.setOnClickListener {
if (tvMain.text.toString().isEmpty()) {
// if the entered number is empty we are displaying an error message.
Toast.makeText(this, "Please enter a valid number..", Toast.LENGTH_SHORT).show()
} else {
// on below line we are getting int value
// and calculating the factorial value of the entered number.
val value: Int = tvMain.text.toString().toInt()
val fact: Int = factorial(value)
tvMain.setText(fact.toString())
tvsec.text = "$value`!"
}
}
}
fun factorial(n: Int): Int {
// this method is use to find factorial
return if (n == 1 || n == 0) 1 else n * factorial(n - 1)
}
fun evaluate(str: String): Double {
return object : Any() {
// on below line we are creating variable
// for tracking the position and char pos.
var pos = -1
var ch = 0
// below method is for moving to next character.
fun nextChar() {
// on below line we are incrementing our position
// and moving it to next position.
ch = if (++pos < str.length) str[pos].toInt() else -1
}
// this method is use to check the extra space
// present int the expression and removing it.
fun eat(charToEat: Int): Boolean {
while (ch == ' '.toInt()) nextChar()
// on below line we are checking the char pos
// if both is equal then we are returning it to true.
if (ch == charToEat) {
nextChar()
return true
}
return false
}
// below method is to parse our
// expression and to get the ans
// in this we are calling a parse
// expression method to calculate the value.
fun parse(): Double {
nextChar()
val x = parseExpression()
if (pos < str.length) throw RuntimeException("Unexpected: " + ch.toChar())
return x
}
// in this method we will only perform addition and
// subtraction operation on the expression.
fun parseExpression(): Double {
var x = parseTerm()
while (true) {
if (eat('+'.toInt())) x += parseTerm() // addition
else if (eat('-'.toInt())) x -= parseTerm() // subtraction
else return x
}
}
// in below method we will perform
// only multiplication and division operation.
fun parseTerm(): Double {
var x = parseFactor()
while (true) {
if (eat('*'.toInt())) x *= parseFactor() // multiplication
else if (eat('/'.toInt())) x /= parseFactor() // division
else return x
}
}
// below method is use to parse the factor
fun parseFactor(): Double {
//on below line we are checking for addition
// and subtraction and performing unary operations.
if (eat('+'.toInt())) return parseFactor() // unary plus
if (eat('-'.toInt())) return -parseFactor() // unary minus
// creating a double variable for ans.
var x: Double
// on below line we are creating
// a variable for position.
val startPos = pos
// on below line we are checking
// for opening and closing parenthesis.
if (eat('('.toInt())) { // parentheses
x = parseExpression()
eat(')'.toInt())
} else if (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) {
// numbers
while (ch >= '0'.toInt() && ch <= '9'.toInt() || ch == '.'.toInt()) nextChar()
// on below line we are getting sub string from our string using start and pos.
x = str.substring(startPos, pos).toDouble()
} else if (ch >= 'a'.toInt() && ch <= 'z'.toInt()) {
// on below function we are checking for the operator in our expression.
while (ch >= 'a'.toInt() && ch <= 'z'.toInt()) nextChar()
val func = str.substring(startPos, pos)
// calling a method to parse our factor.
x = parseFactor()
// on below line we are checking for square root.
x =
if (func == "sqrt") Math.sqrt(x)
// on below line we are checking for sin function
// and calculating sin function using Math class.
else if (func == "sin") Math.sin(
Math.toRadians(x)
// on below line we are calculating the cos value
) else if (func == "cos") Math.cos(
Math.toRadians(x)
// on below line we are calculating
// the tan value of our expression.
) else if (func == "tan")
Math.tan(Math.toRadians(x))
// on below line we are calculating
// log value of the expression.
else if (func == "log")
Math.log10(x)
// on below line we are calculating
// ln value of expression.
else if (func == "ln") Math.log(x)
// f we get any error then
// we simply return the exception.
else throw RuntimeException(
"Unknown function: $func"
)
} else {
// if the condition not satisfy then we are returning the exception
throw RuntimeException("Unexpected: " + ch.toChar())
}
// on below line we are calculating the power of the expression.
if (eat('^'.toInt())) x = Math.pow(x, parseFactor()) // exponentiation
return x
}
// at last calling a parse for our expression.
}.parse()
}
}
BEST OF LUCK
Commentaires