MAD Practicals
MAD Practicals
MAD Practicals
Practical-1
Aim : Installation of Android in Windows with Simulator and Introduction to Android
Life Cycle & Introduction to UI/XI.
Software Required: None
Knowledge Required: Basics of Android like LifeCycle
The Android Software Development Kit (referred to in this License Agreement as the "SDK" and
specifically including the Android system files, packaged APIs, and Google APIs add-ons) is
licensed to you subject to the terms of this License Agreement. This License Agreement forms a
legally binding contract between you and Google in relation to your use of the SDK. You can
install android studio by following link:
CSPIT(CE) 1|Page
CE373 D17CE144
The Android SDK does not include everything you need to start developing. The SDK separates
tools, platforms, and other components into packages you can download as needed using the
Android SDK Manager. So before you can start, there are a few packages you should add to your
Android SDK.
To start adding packages, launch the Android SDK Manager in one of the following ways:
CSPIT(CE) 2|Page
CE373 D17CE144
As a minimum when setting up the Android SDK, you should download the latest tools and Android
platform:
1. Open the Tools directory and select:
o Android SDK Tools o Android SDK Platform-tools o Android SDK Build-tools
(highest version)
2. Open the first Android X.X folder (the latest version) and select:
o SDK Platform
o A system image for the emulator, such as ARM EABI v7a System Image
CSPIT(CE) 3|Page
CE373 D17CE144
Note: Google Play services APIs are not available on all Android-powered devices, but are
available on all devices with Google Play Store. To use these APIs in the Android emulator, you
must also install the Google APIs system image from the latest Android X.X directory in the SDK
Manager.
By default, Android Studio displays your project files in the Android project view. This view shows
a flattened version of your project's structure that provides quick access to the key source files of
Android projects and helps you work with the Gradle-based build system. The Android project
view:
• Shows the most important source directories at the top level of the module hierarchy.
• Groups the build files for all modules in a common folder.
• Groups all the manifest files for each module in a common folder.
• Shows resource files from all Gradle source sets.
• Groups resource files for different locales, orientations, and screen types in a single group per
resource type.
CSPIT(CE) 4|Page
CE373 D17CE144
The Android project view shows all the build files at the top level of the project hierarchy under
Gradle Scripts. Each project module appears as a folder at the top level of the project hierarchy
and contains four elements.
Click the Android Virtual Device Manager in the toolbar to open it and create new virtual
devices for running your app in the emulator.
The AVD Manager comes with emulators for Nexus 6 and Nexus 9 devices and also supports
creating custom Android device skins based on specific emulator properties and assigning those
skins to hardware profiles. Android Studio installs the Intel® x86 Hardware Accelerated Execution
Manager (HAXM) emulator accelerator and creates a default emulator for quick app prototyping.
For more information, see Managing AVDs.
CSPIT(CE) 5|Page
CE373 D17CE144
Method Description
onResume called when activity will start interacting with the user.
CSPIT(CE) 6|Page
CE373 D17CE144
CSPIT(CE) 7|Page
CE373 D17CE144
Practical-2
Aim :
I. Create “Hello World” application. That will display “Hello World” in the
middle of the screen in the red colour with white background.
II. To understand Activity, Intent Create sample application with login module.
(Check username and password) On successful login, go to next screen. And
on failing login, alert user using Toast. Also pass username to next screen.
III. Create “Hello World” application. That will display “Hello World” in the
middle of the screen in the red color with white background
Activity_main.xml:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.jBharg11.myapplication.MainActivity">
<TextView
android:id="@+id/tvHello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_margin="40dp"
android:padding="50dp"
android:gravity="center"
android:text="Hello world!"
android:textColor="@color/colorRed"
android:textSize="52sp"
android:textStyle="bold|italic" />
</LinearLayout>
CSPIT(CE) 8|Page
CE373 D17CE144
OUTPUT:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:text="Login"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:hint="Username">
<requestFocus />
CSPIT(CE) 9|Page
CE373 D17CE144
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="Login" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Mainactivity.java
package com.example.jBharg11.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
CSPIT(CE) 10 | P a g e
CE373 D17CE144
bt1.setOnClickListener(new View.OnClickListener()
{
if(et1.getText().toString().equals("adarsh") &&
et2.getText().toString().equals("adarsh") )
{
Intent i = new
Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(), "Invalid
Userid/Password", Toast.LENGTH_LONG).show();
}
}
});
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Activity_main2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
CSPIT(CE) 11 | P a g e
CE373 D17CE144
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Welcome to Activity 2"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
main2activity.java
package com.example.jBharg11.myapplication;
import android.app.Activity;
import android.os.Bundle; import
android.view.Menu; import
android.view.MenuItem;
if (id == R.id.action_settings)
{
return true;
}
CSPIT(CE) 12 | P a g e
CE373 D17CE144
return super.onOptionsItemSelected(item);
}
}
Output:
CSPIT(CE) 13 | P a g e
CE373 D17CE144
Practical-3
Aim : Create login application where you will have to validate EmailID (UserName). Till
the username andpassword is not validated , login button should remain disabled. Create
and Login application as above . On successful login , open browser with any URL
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginTop="52dp"
android:layout_toLeftOf="@+id/editText2"
android:text="Password"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_cont
ent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignTop="@+id/textView2"
android:ems="10"
android:inputType="textPassword" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
mainactivity.java
package com.example.jBharg11.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri; import
android.os.Bundle; import
android.view.Menu; import
CSPIT(CE) 14 | P a g e
CE373 D17CE144
android.view.MenuItem; import
android.view.View; import
android.widget.Button; import
android.widget.EditText;
et1 = (EditText)
findViewById(R.id.editText1); et2 =
(EditText) findViewById(R.id.editText2);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener()
{
@Override public void onClick(View v)
{
String s1 = et1.getText().toString();
String s2 = et2.getText().toString();
startActivity(i);
}
}
});
}
CSPIT(CE) 15 | P a g e
CE373 D17CE144
Output:
CSPIT(CE) 16 | P a g e
CE373 D17CE144
Practical-4
Aim:
Create an application that will pass some number to the next screen, and on the next
screen that number of items should be display in the list.
Understand resource folders: Create spinner with strings taken from resource folder (res
>> value folder).
On changing spinner value, change image. Understand Menu option. Create an
application that will change colour of the screen, based on selected options from the menu
Create an application that will pass some number to the next screen, and on the next
screen that number of items should be display in the list.
Activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Enter Number (1-10)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
CSPIT(CE) 17 | P a g e
CE373 D17CE144
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Next" />
</RelativeLayout>
Activity_main2.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity2" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content
"
android:layout_above="@+id/textVie
w2"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textVie
w1"
android:layout_marginTop="24dp" >
</ListView>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="List Items" />
</RelativeLayout>
MainActivity.java:
package com.example.jBharg11.myapplication;
CSPIT(CE) 18 | P a g e
CE373 D17CE144
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
b1 = (Button) findViewById(R.id.button1);
et1 = (EditText) findViewById(R.id.editText1);
b1.setOnClickListener(new View.OnClickListener()
{
@Override public void onClick(View arg0)
{
Intent i = new
Intent(getApplicationContext(),MainActivity2.class);
i.putExtra("parameter1", et1.getText().toString());
startActivity(i);
}
});
}
MainActivity2.java:
package com.example.jBharg11.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
CSPIT(CE) 19 | P a g e
CE373 D17CE144
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
int n = Integer.parseInt(receiveValue);
String generatedCsvString="";
for(int i = 1;i<=n;i++)
{
generatedCsvString += "Item : " + i + ",";
}
arrayOfItems = generatedCsvString.split(",");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,android.R.id.text1,arrayOfItems);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new OnItemClickListener()
{
CSPIT(CE) 20 | P a g e
CE373 D17CE144
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Output:
Create spinner with strings taken from resource folder (res >> value folder). On changing spinner
value, change image.
Activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/spinner1" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:entries="@array/S"
/>
<ImageView
android:id="@+id/imageView1" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignTop="@+id/imageView1"
android:layout_marginTop="32dp"
android:layout_toRightOf="@+id/imageView1" />
</RelativeLayout>
MainActivity.java:
import android.os.Bundle;
CSPIT(CE) 21 | P a g e
CE373 D17CE144
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener; import
android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
@Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Toast.makeText(this,"SELECTED ITEM IS :
"+arg0.getSelectedItem().toString(),Toast.LENGTH_SHORT).show();
Output:
CSPIT(CE) 22 | P a g e
CE373 D17CE144
Create an application that will change color of the screen, based on selected options from the
menu Activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/mainactivity">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hit Menu Button"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
MainActivity.java:
package com.example.jBharg11.myapplication;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
return true;
CSPIT(CE) 23 | P a g e
CE373 D17CE144
if(item.getTitle().equals("Red"))
{
view1.setBackgroundColor(Color.RED);
}
else if(item.getTitle().equals("Green"))
{
view1.setBackgroundColor(Color.GREEN);
}
else if(item.getTitle().equals("Blue"))
{
view1.setBackgroundColor(Color.BLUE);
}
return super.onOptionsItemSelected(item);
}
}
Output:
Conclusion: resource folder contains many important folders for Android development. Data can be
passed between activities.
CSPIT(CE) 24 | P a g e
CE373 D17CE144
Practical 5
Aim : Create an application that will display toast(Message) on specific interval of
time. Create an background application that will open activity on specific time. Create
an application that will have spinner with list of animation names. On selecting
animation name , that animation should affect on the images displayed below.
Software Required: Android Studio
Knowledge Required: Toast message, animation properties
Code :
Create an application that will display toast (Message) on specific interval of time.
activity_main.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text will display after"
app:layout_constraintBottom_toBottomOf="pa
rent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent
"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<Chronometer
android:id="@+id/timer"
android:layout_width="112dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Chronometer"
android:textAlignment="center"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent
"
app:layout_constraintStart_toStartOf="pare
nt"
CSPIT(CE) 25 | P a g e
CE373 D17CE144
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="START"
app:layout_constraintEnd_toEndOf="parent
"
app:layout_constraintStart_toStartOf="pare
nt"
app:layout_constraintTop_toBottomOf="@+id/editText" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:layout_marginEnd="40
dp"
android:layout_marginTop="64
dp" android:ems="10"
android:hint="Enter Time"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="pare
nt"
app:layout_constraintTop_toTopOf="pare
nt" />
<TextView
android:id="@+id/textView2"
android:layout_width="93dp"
android:layout_height="44dp"
android:layout_marginEnd="264dp"
android:layout_marginTop="64dp"
android:text="Time"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="p
arent"
app:layout_constraintTop_toTopOf="p
arent" tools:text="TIME" />
</android.support.constraint.ConstraintLayout>
activity_main2.xml
CSPIT(CE) 26 | P a g e
CE373 D17CE144
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=".Main2Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarO
verlay">
<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.PopupO
verlay" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_c
ontent"
android:layout_gravity="bottom
|end"
android:layout_margin="@dimen/fab_margi
n"
app:srcCompat="@android:drawable/ic_dial
og_email" />
</android.support.design.widget.CoordinatorLayout>
MainActivity.java
package com.example.jainilpatel.myapplication;
import android.content.Intent;
import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import
android.view.View;
import
android.widget.Button
;
CSPIT(CE) 27 | P a g e
CE373 D17CE144
import
android.widget.Chronometer;
import
android.widget.EditText;
import
android.widget.TextView;
import android.widget.Toast;
c.start();
c.setOnChronometerTickList
ener(new
Chronometer.OnChronometerTickListener() {
@Override
public void onChronometerTick(Chronometer chronometer)
{ t.setText("Your text will be displayed after "+(time-
i)+" Seconds");
i++; if(time-
i==-
1&&count>0)
{
Toast.makeText(MainActivity.this,
"MESSAGE DISPLAYED", Toast.LENGTH_SHORT).show();
i=0;
Intent
intent=new
Intent(MainActivity.this,Main2Activity.class)
;
intent.putExtra("time",String.valueOf(time));
startActivity(
intent);
count--;
}
if(count==0)
{
c.stop();
}
}
});
CSPIT(CE) 28 | P a g e
CE373 D17CE144
}
});
}
}
Main2Activity.java
package com.example.jainilpatel.myapplication;
import
android.content.Intent;
import
android.os.Bundle;
import
android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import
android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i=getIntent();
Integer t=Integer.parseInt(i.getStringExtra("time"));
FloatingActionButton fab =
(FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own
action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
final Handler handler = new
Handler();
handler.postDelayed(new
Runnable() {
@Override
public void run() {
//Do something after ms
Main2Activity.super.onBackPre
ssed();
}
}, t*1000);
CSPIT(CE) 29 | P a g e
CE373 D17CE144
//startActivity(new Intent(Main2Activity.this,MainActivity.class));
}
}
OUTPUT:
Activity_main.xml
<ImageView
android:id="@+id/imageView"
android:layout_width="318dp"
android:layout_height="328dp"
CSPIT(CE) 30 | P a g e
CE373 D17CE144
android:layout_marginBottom="32dp"
android:src="@drawable/i1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<Spinner
android:id="@+id/spinner"
android:layout_width="292dp"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.jBharg11.practical5animations;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
spnr=(Spinner) findViewById(R.id.spinner);
imgmaster=(ImageView) findViewById(R.id.imageView);
adapter =
ArrayAdapter.createFromResource(this,R.array.Animation,android.R.layout.simple_spinner_i
tem);
spnr.setAdapter(adapter);
spnr.setOnItemSelectedListener(this);
}
CSPIT(CE) 31 | P a g e
CE373 D17CE144
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l)
{
Animation anim = AnimationUtils.loadAnimation(this,R.anim.alpha);
if(spnr.getSelectedItem().equals("Alpha")){
anim = AnimationUtils.loadAnimation(this,R.anim.alpha);
}
else if(spnr.getSelectedItem().equals("Rotate")){
anim = AnimationUtils.loadAnimation(this,R.anim.rotate);
}
else if(spnr.getSelectedItem().equals("Scale")){
anim = AnimationUtils.loadAnimation(this,R.anim.scale);
}
else if(spnr.getSelectedItem().equals("Spin")){
anim = AnimationUtils.loadAnimation(this,R.anim.spin);
}
else if(spnr.getSelectedItem().equals("Translate")){
anim = AnimationUtils.loadAnimation(this,R.anim.translate);
}
imgmaster.startAnimation(anim);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Output :
CSPIT(CE) 32 | P a g e
CE373 D17CE144
CODE:
Create an application that will have spinner with list of animation names. On selecting animation
name, that animation should affect on the images displayed below.
activity_main.xml
<ImageView
android:id="@+id/imageView"
android:layout_width="318dp"
android:layout_height="328dp"
android:layout_marginBottom="32dp"
android:src="@drawable/i1"
app:layout_constraintBottom_toBottomOf="par
ent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
/>
<Spinner
android:id="@+id/spinner"
android:layout_width="292dp"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
app:layout_constraintLeft_toLeftOf="parent
"
CSPIT(CE) 33 | P a g e
CE373 D17CE144
app:layout_constraintRight_toRightOf="par
ent"
app:layout_constraintTop_toTopOf="parent
" />
</android.support.constraint.ConstraintLayout>
res\anim\alpha.xml
res\anim\rotate.xml
android:toDegr
ees="-360"
android:pivotX
="50%"
android:pivotY
="50%"
android:duratio
n="7000" />
</set>
res\anim\scale.xml
CSPIT(CE) 34 | P a g e
CE373 D17CE144
</set>
res\nim\spin.xml
res\nim\translate.xml
MainActivity.java
package com.example.jBharg11.practical5animations;
import android.support.v7.app.AppCompatActivity;
import
android.os.Bundle;
import
android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import
android.widget.ArrayAdapter;
import android.widget.ImageView;
CSPIT(CE) 35 | P a g e
CE373 D17CE144
import android.widget.Spinner;
spnr=(Spinner) findViewById(R.id.spinner);
imgmaster=(ImageView)
findViewById(R.id.imageView);
adapter =
ArrayAdapter.createFromResource(this,R.array.Animation,android.R.layout.simple_
spinner_item);
spnr.setAdapter(adapter);
spnr.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int
position, long l) {
Animation anim = AnimationUtils.loadAnimation(this,R.anim.alpha);
if(spnr.getSelectedItem().equals("Alpha")){
anim = AnimationUtils.loadAnimation(this,R.anim.alpha);
}
else if(spnr.getSelectedItem().equals("Rotate")){
anim = AnimationUtils.loadAnimation(this,R.anim.rotate);
}
else if(spnr.getSelectedItem().equals("Scale")){
anim = AnimationUtils.loadAnimation(this,R.anim.scale);
}
else if(spnr.getSelectedItem().equals("Spin")){
anim = AnimationUtils.loadAnimation(this,R.anim.spin);
}
else if(spnr.getSelectedItem().equals("Translate")){
anim = AnimationUtils.loadAnimation(this,R.anim.translate);
}
imgmaster.startAnimation(anim);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
CSPIT(CE) 36 | P a g e
CE373 D17CE144
OUTPUT:
CONCLUSION:
Data can be display for some time via toast. Animation is available in Android library.
CSPIT(CE) 37 | P a g e
CE373 D17CE144
Practical 6
Aim : Understanding of UI : Create an UI such that , one screen have list of all the types
of cars. On selecting of any car name, next screen should show Car details like : name ,
launched date ,company name, images(using gallery) if available, show different colors
in which it is available.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="gtu.android.prog11.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:text="Select Your Favourit Car"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:entries="@array/car_names"
android:layout_marginTop="21dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="34dp"
android:text="Developed By:Adarsh Patel"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
CSPIT(CE) 38 | P a g e
CE373 D17CE144
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/spinner1"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp"
android:text="Go !" />
</RelativeLayout>
activity_main2.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="gtu.android.prog11.MainActivity2" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="23dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Gallery
android:id="@+id/gallery1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
CSPIT(CE) 39 | P a g e
CE373 D17CE144
import android.widget.Button;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
Spinner sp1;
int cartype;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//=======================================================
// Calling another activity to display car information.
// passing car index along with it.
//=======================================================
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
i.putExtra("cartype", cartype + "");
startActivity(i);
}
});
//=====================================================
// When use select car, put it into some variable so later on we can pass this
//====================================================
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
@Override
public void onNothingSelected(AdapterView<?> arg0) {
CSPIT(CE) 40 | P a g e
CE373 D17CE144
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
}
MainActivity2.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
TextView tvCarName,tvcarDetails;
Gallery gallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
//=================================================================
====
//Read Car index value from the intent, sent using previus activity intent
//=================================================================
CSPIT(CE) 41 | P a g e
CE373 D17CE144
====
int carType = Integer.parseInt( getIntent().getStringExtra("cartype"));
//=================================================================
====
// Display car information into TextView as per parameter
//=================================================================
====
if(carType == 0)
{
tvCarName.setText("You Love Maruti 800");
tvcarDetails.setText("Car was Launched on 2000 \nCompany : Maruti");
}
else if(carType == 1)
{
tvCarName.setText("Its Duster !");
tvcarDetails.setText("Car was Launched on 1980 \nCompany : Abc");
}
else if(carType == 2)
{
tvCarName.setText("Its Scorpio");
tvcarDetails.setText("Car was Launched on 2005 \nCompany : PQR");
}
//=================================================================
====
// Load image gallery as per selection
//=================================================================
====
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
CSPIT(CE) 42 | P a g e
CE373 D17CE144
return super.onOptionsItemSelected(item);
}
//==================================================
// Customer Adapter to add Images into Gallery
//==================================================
class CustomAdapterForGallery extends BaseAdapter
{
int GalItemBg;
private Context currentContext;
String CarIndexInString;
//========================================================
// Resource Image Array
//========================================================
private Integer[] imagearray1 = {R.drawable.a1, R.drawable.a2};
private Integer[] imagearray2 = {R.drawable.b1, R.drawable.b2};
private Integer[] imagearray3 = {R.drawable.c1, R.drawable.c2};
CSPIT(CE) 43 | P a g e
CE373 D17CE144
if(CarIndexInString.equals("0"))
{
imgView.setImageResource(imagearray1[position]);
}
else if(CarIndexInString.equals("1"))
{
imgView.setImageResource(imagearray2[position]);
}
else if(CarIndexInString.equals("2"))
{
imgView.setImageResource(imagearray3[position]);
}
else
{
imgView.setImageResource(imagearray1[position]);
}
return imgView;
}
}
CSPIT(CE) 44 | P a g e
CE373 D17CE144
OUTPUT
Conclusion: Data can be passed between different activities. Elemetns can be set during run time as
per user wanted.
CSPIT(CE) 45 | P a g e
CE373 D17CE144
Practical 7
Aim : Create an application to call specific entered number by user in the EditText.
Create an application that will create database with table of User credential.
Create an application to read file from asset folder and copy it in memory card.
Create an application that will play a media file from the memory card. Create an
application to make Insert , update , Delete and retrieve operation on the
database.
In manifest:
<uses-permission android:name="android.permission.CALL_PHONE"/>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#90CAF9"
tools:context="gtu.andriod.prog14.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
CSPIT(CE) 46 | P a g e
CE373 D17CE144
android:layout_centerHorizontal="true"
android:textColor="#1565C0"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="52dp"
android:ems="10"
android:textColor="#000000"
android:textColorHint="#000000"
android:inputType="phone" />
<Button
android:id="@+id/button1"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_alignBottom="@+id/editText1"
android:layout_toRightOf="@+id/editText1"
android:background="@drawable/call"
CSPIT(CE) 47 | P a g e
CE373 D17CE144
android:text=""
android:textColor="#000000" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:textColor="#1565C0"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
ActivityMain.java
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
EditText et1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CSPIT(CE) 48 | P a g e
CE373 D17CE144
b1 = (Button) findViewById(R.id.button1);
et1 = (EditText) findViewById(R.id.editText1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//============================================
// Intnet used to call on Custom Number (As per EditText1
value)
// First add (CALL_PHONE) permission before using following
code
//===========================================
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:" + et1.getText().toString() ));
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
OUTPUT:
CSPIT(CE) 49 | P a g e
CE373 D17CE144
Create an application that will create database with table of User credential.
Java:
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
String Data="";
/* Create a Database. */
try
{
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
CSPIT(CE) 50 | P a g e
CE373 D17CE144
package kmn.Fifteen;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
CSPIT(CE) 51 | P a g e
CE373 D17CE144
/**
* Create a Database.
* */
try
{
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
myDB.execSQL("DROP TABLE IF EXISTS "+TableName+";");
}
catch(Exception e)
{
Log.e("Error", "Error", e);
}
finally
{
if (myDB != null)
myDB.close();
}
}
}
Create an application to read file from asset folder and copy it in memory card.
Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fce4ec"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="gtu.android.prog16.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
CSPIT(CE) 52 | P a g e
CE373 D17CE144
android:layout_height="wrap_content"
android:textColor="#e91e63"
android:text="Read File from assets and Write into sdcard (external storage)"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:textColor="#9e9e9e"
android:text="Developed By: Adarsh Patel"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text=""
android:textColor="#d81b60"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
MainActivity.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
CSPIT(CE) 53 | P a g e
CE373 D17CE144
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
TextView tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
InputStream is = getResources().getAssets().open("readme.txt");
//===============================================
// Read data of readme.txt in byte format and store into b array
//==============================================
byte[] b = new byte[is.available()];
String locationToStoreFile =
Environment.getExternalStorageDirectory().getPath() + "/readme.txt";
CSPIT(CE) 54 | P a g e
CE373 D17CE144
//Toast.makeText(getApplicationContext(), ,
Toast.LENGTH_SHORT).show();
//==========================================
// Write byte array data into file output stream object, location is external
storage
//==========================================
fos.write(b);
fos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
CSPIT(CE) 55 | P a g e
CE373 D17CE144
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
OUTPUT:
CSPIT(CE) 56 | P a g e
CE373 D17CE144
Create an application that will play a media file from the memory card.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fce4ec"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="gtu.android.prog17.MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#e91e63"
android:text="Play media file from memory card"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:textColor="#9e9e9e"
android:text="Developed By: Adarsh Patel"
android:textAppearance="?android:attr/textAppearanceLarge" />
CSPIT(CE) 57 | P a g e
CE373 D17CE144
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text=""
android:textColor="#d81b60"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
MediaPlayer mp1;
TextView tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CSPIT(CE) 58 | P a g e
CE373 D17CE144
mp1 = MediaPlayer.create(this,
Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/media1.mp3"));
mp1.setLooping(true);
mp1.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
OUTPUT:
CSPIT(CE) 59 | P a g e
CE373 D17CE144
CSPIT(CE) 60 | P a g e
CE373 D17CE144
Create an application to make Insert , update , Delete and retrieve operation on the database.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Surname"
android:id="@+id/textView2"
android:layout_below="@+id/editText_name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Marks"
android:id="@+id/textView3"
android:layout_below="@+id/editText_surname"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_name"
android:layout_alignTop="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_surname"
android:layout_alignTop="@+id/textView2"
CSPIT(CE) 61 | P a g e
CE373 D17CE144
android:layout_toRightOf="@+id/textView2"
android:layout_toEndOf="@+id/textView2" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_Marks"
android:layout_below="@+id/editText_surname"
android:layout_toRightOf="@+id/textView3"
android:layout_toEndOf="@+id/textView3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Data"
android:id="@+id/button_add"
android:layout_below="@+id/editText_Marks"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="76dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View All"
android:id="@+id/button_viewAll"
android:layout_above="@+id/button_update"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:id="@+id/button_update"
android:layout_below="@+id/button_add"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:id="@+id/button_delete"
android:layout_centerVertical="true"
android:layout_below="@+id/button_viewAll"
android:layout_alignLeft="@+id/button_viewAll"
android:layout_alignStart="@+id/button_viewAll" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="id"
android:id="@+id/textView_id"
CSPIT(CE) 62 | P a g e
CE373 D17CE144
android:layout_below="@+id/editText_Marks"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText_id"
android:layout_alignTop="@+id/textView_id"
android:layout_toRightOf="@+id/textView3"
android:layout_toEndOf="@+id/textView3" />
</RelativeLayout>
DatabaseHelper.java
package com.example.programmingknowledge.sqliteapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by ProgrammingKnowledge on 4/3/2015.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "SURNAME";
public static final String COL_4 = "MARKS";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
CSPIT(CE) 63 | P a g e
CE373 D17CE144
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
MainActivity.java
package com.example.programmingknowledge.sqliteapp;
import android.app.AlertDialog;
import android.database.Cursor;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
Button btnviewUpdate;
CSPIT(CE) 64 | P a g e
CE373 D17CE144
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editSurname = (EditText)findViewById(R.id.editText_surname);
editMarks = (EditText)findViewById(R.id.editText_Marks);
editTextId = (EditText)findViewById(R.id.editText_id);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
btnviewUpdate= (Button)findViewById(R.id.button_update);
btnDelete= (Button)findViewById(R.id.button_delete);
AddData();
viewAll();
UpdateData();
DeleteData();
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
if(deletedRows > 0)
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Deleted",Toast.LENGTH_LONG).show();
}
}
);
}
public void UpdateData() {
btnviewUpdate.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
editName.getText().toString(),
editSurname.getText().toString(),editMarks.getText().toString());
if(isUpdate == true)
Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Updated",Toast.LENGTH_LONG).show();
}
}
);
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
@Override
CSPIT(CE) 65 | P a g e
CE373 D17CE144
@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;
CSPIT(CE) 66 | P a g e
CE373 D17CE144
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
OUTPUT:
Conclusion: User can retrive data and add data using SQLite database via Android Studio..
CSPIT(CE) 67 | P a g e
CE373 D17CE144
Practical 8
Aim : Create an application to read file from the sdcard and display that file content to
the screen. Create an application to draw line on the screen as user drag his finger. Create
an application to send message between two emulators. Create an application to take
picture using native application.
activity_main.xml
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#fce4ec”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”gtu.android.prog19.MainActivity” >
<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textColor=”#e91e63″
android:text=”Read file from SDCard”
android:textAppearance=”?android:attr/textAppearanceLarge” />
<TextView
android:id=”@+id/textView2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_centerHorizontal=”true”
android:layout_marginBottom=”52dp”
android:textColor=”#9e9e9e”
android:text=”Developed By: Adarsh Patel”
android:textAppearance=”?android:attr/textAppearanceLarge” />
<TextView
android:id=”@+id/textView3″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:text=””
android:textColor=”#d81b60″
android:textAppearance=”?android:attr/textAppearanceLarge” />
</RelativeLayout>
CSPIT(CE) 68 | P a g e
CE373 D17CE144
MainActivity.java
mport java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
TextView tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//===========================================
// File path we want to read (current path : sdcard/readme.txt)
//==========================================
File file = new File( Environment.getExternalStorageDirectory() + “/readme.txt”);
//===========================================
// string builder object to hold intermediate data.
//==========================================
StringBuilder sb = new StringBuilder();
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//===========================================
// read line by line data.
//==========================================
while ((line = br.readLine()) != null)
{
sb.append(line);
sb.append(‘\n’);
}
br.close();
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(), “Error While Reading File”,
Toast.LENGTH_LONG).show();
}
//===========================================
CSPIT(CE) 69 | P a g e
CE373 D17CE144
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
OUTPUT:
AIM: Create an application to draw line on the screen as user drag his finger.
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
CSPIT(CE) 70 | P a g e
CE373 D17CE144
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(new TouchEventExample(getApplicationContext()));
return super.onOptionsItemSelected(item);
}
}
TouchEventExample.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
float x1,x2,y1,y2;
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
//super.onDraw(canvas);
//=====================================
//Set Line Width
//=====================================
paint.setStrokeWidth(3.4f);
//=============================================
//Draw Line from X to Y (As per Click)
//============================================
canvas.drawLine(x1, y1, x2, y2, paint);
CSPIT(CE) 71 | P a g e
CE373 D17CE144
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction())
{
//=======================================================================
======
//Case to detect Down Event (Means When you Press Screen This Event will occure)
//=======================================================================
======
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
y1 = event.getY();
return true;
//=======================================================================
======
//Case to detect Move Event
//=======================================================================
======
case MotionEvent.ACTION_MOVE:
x2 = event.getX();
y2 = event.getY();
break;
default:
return false;
}
//======================================
//call redraw
//======================================
invalidate();
return false;
}
}
OUTPUT:
CSPIT(CE) 72 | P a g e
CE373 D17CE144
MainActivity.java
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
PendingIntent pi;
SmsManager sms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//======================================
// Get all pending Activity
//======================================
String msg = “android.telephony.SmsManager.STATUS_ON_ICC_SENT”;
PendingIntent piSent = PendingIntent.getBroadcast(MainActivity.this, 0,new Intent(msg), 0);
//======================================
// Send SMS Using Default SMS Manager
//======================================
sms = SmsManager.getDefault();
sms.sendTextMessage(“5556”, null, “This is sample test message”, piSent, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
CSPIT(CE) 73 | P a g e
CE373 D17CE144
activity_main.xml
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”com.example.gtu_android_prog21.MainActivity” >
<TextView
android:id=”@+id/textView1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”45dp”
android:gravity=”center_horizontal”
android:text=”Send Message to emulators programmatically”
android:textAppearance=”?android:attr/textAppearanceLarge” />
</RelativeLayout>
OUTPUT:
Manifest
Give permission in manifest file as "android.permission.CAMERA"
Java
import android.app.Activity;
import android.content.Intent;
CSPIT(CE) 74 | P a g e
CE373 D17CE144
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
ImageView img;
Button btcapture;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img=(ImageView) findViewById(R.id.imageView1);
btcapture=(Button) findViewById(R.id.buttoncapture);
btcapture.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myintent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(myintent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap myimage=(Bitmap) data.getExtras().get("data");
img.setImageBitmap(myimage);
}
}
Conclusion: Native applications can be used with proper permission access. SD card can also be
accessed to store or retrive data.
CSPIT(CE) 75 | P a g e
CE373 D17CE144
Practical 9
Aim : Create an application to pick up any image from the native application gallery and
display it on the screen. Create an application to open any URL inside the application
and clicking on any link from that URl should not open Native browser but that URL
should open the same screen.
JAVA:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
@Override
public void onClick(View arg0) {
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
CSPIT(CE) 76 | P a g e
CE373 D17CE144
}
}
OUTPUT:
CSPIT(CE) 77 | P a g e
CE373 D17CE144
AIM: Create an application to open any URL inside the application and clicking on any link
from that URl should not open Native browser but that URL should open the same screen.
Java:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
CSPIT(CE) 78 | P a g e
CE373 D17CE144
TextView edurl;
Button btgo;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web=(WebView) findViewById(R.id.webView1);
edurl=(TextView) findViewById(R.id.editTexturl);
btgo=(Button) findViewById(R.id.buttongo);
btgo.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(edurl.getText().toString().equals(""))
{
Toast.makeText(this, "Pls Enter URL...", 1).show();
}
else
{
String stringurl=edurl.getText().toString();
Conclusion: Gallary can be accessed with proper permission to access gallery data. Webview is used
to show any website inside local application itself.
CSPIT(CE) 79 | P a g e
CE373 D17CE144
Practical 10
AIM: Introduction to Xcode, Swift, and the iOS SDK and App Design
System Requirement: None
Knowledge Requirement: Basics of Xcode, swift
Xcode:
Xcode is an integrated development environment (IDE) for macOS containing a suite of software
development tools developed by Apple for developing software for macOS, iOS, watchOS, and tvOS.
First released in 2003, the latest stable release is version 10.0 and is available via the Mac App Store
free of charge for macOS High Sierra users. Registered developers can download preview releases and
prior versions of the suite through the Apple Developer website.
Major features:
Xcode supports source code for the programming languages C, C++, Objective-C, Objective-C++, Java,
AppleScript, Python, Ruby, ResEdit (Rez), and Swift, with a variety of programming models, including
but not limited to Cocoa, Carbon, and Java. Third parties have added support for GNU Pascal, Free
Pascal,Ada,C#, Perl, D and Fortran.
Xcode can build fat binary files containing code for multiple architectures with the Mach-O executable
format. These are called universal binary files, which allow software to run on both PowerPC and Intel-
based (x86) platforms and that can include both 32-bit and 64-bit code for both architectures. Using the
iOS SDK, Xcode can also be used to compile and debug applications for iOS that run on ARM
architecture processors.
Xcode includes the GUI tool Instruments, which runs atop a dynamic tracing framework, DTrace,
created by Sun Microsystems and released as part of OpenSolaris.
Swift:
Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc.
for iOS, macOS, watchOS, tvOS, and Linux. Swift is designed to work with Apple's Cocoa and Cocoa
Touch frameworks and the large body of existing Objective-C code written for Apple products. It is
built with the open source LLVM compiler framework and has been included in Xcode since version
6. On platforms other than Linux, it uses the Objective-C runtime library which allows C, Objective-C,
C++ and Swift code to run within one program.
Apple intended Swift to support many core concepts associated with Objective-C, notably dynamic
dispatch, widespread late binding, extensible programming and similar features, but in a "safer" way,
making it easier to catch software bugs; Swift has features addressing some common programming
errors like null pointer dereferencing and provides syntactic sugar to help avoid the pyramid of doom.
Swift supports the concept of protocol extensibility, an extensibility system that can be applied to types,
structs and classes, which Apple promotes as a real change in programming paradigms they term
"protocol-oriented programming" (similar to traits).
Features of Swift:
Syntactic sugar:
Under the Cocoa and Cocoa Touch environments, many common classes were part of the Foundation
Kit library. This included the NSString string library (using Unicode), the NSArray and NSDictionary
collection classes, and others. Objective-C provided various bits of syntactic sugar to allow some of
CSPIT(CE) 80 | P a g e
CE373 D17CE144
these objects to be created on-the-fly within the language, but once created, the objects were
manipulated with object calls. For instance, in Objective-C concatenating two NSStrings required
method calls similar to this:
NSString *str = @"hello,";
str = [str stringByAppendingString:@" world"];
In Swift, many of these basic types have been promoted to the language's core, and can be manipulated
directly. For instance, strings are invisibly bridged to NSString (when Foundation is imported) and can
now be concatenated with the + operator, allowing greatly simplified syntax; the prior example
becoming:
var str = "hello,"
str += " world"
Access control:
Swift supports five access control levels for symbols: open, public, internal, fileprivate, and private.
Unlike many object-oriented languages, these access controls ignore inheritance hierarchies: private
indicates that a symbol is accessible only in the immediate scope, fileprivate indicates it is accessible
only from within the file, internal indicates it is accessible within the containing module, public
indicates it is accessible from any module, and open (only for classes and their methods) indicates that
the class may be subclassed outside of the module.[45]
An important new feature in Swift is option types, which allow references or values to operate in a
manner similar to the common pattern in C, where a pointermay refer to a value or may be null. This
implies that non-optional types cannot result in a null-pointer error; the compiler can ensure this is not
possible.
Optional types are created with the Optional mechanism—to make an Integer that is nullable, one would
use a declaration similar to var optionalInteger: Optional<Int>. As in C#, Swift also includes syntactic
sugar for this, allowing one to indicate a variable is optional by placing a question mark after the type
name, var optionalInteger: Int?. Variables or constants that are marked optional either have a value of
the underlying type or are nil. Optional types wrap the base type, resulting in a different instance. String
and String? are fundamentally different types, the latter has more in common with Int? than String.
Value types:
In many object-oriented languages, objects are represented internally in two parts. The object is stored
as a block of data placed on the heap, while the name (or "handle") to that object is represented by a
pointer. Objects are passed between methods by copying the value of the pointer, allowing the same
underlying data on the heap to be accessed by anyone with a copy. In contrast, basic types like integers
and floating point values are represented directly; the handle contains the data, not a pointer to it, and
that data is passed directly to methods by copying. These styles of access are termed pass-by-reference
in the case of objects, and pass-by-value for basic types.
Both concepts have their advantages and disadvantages. Objects are useful when the data is large, like
CSPIT(CE) 81 | P a g e
CE373 D17CE144
the description of a window or the contents of a document. In these cases, access to that data is provided
by copying a 32- or 64-bit value, versus copying an entire data structure. However, smaller values like
integers are the same size as pointers (typically both are one word), so there is no advantage to passing
a pointer, versus passing the value. Also, pass-by-reference inherently requires a dereferencing
operation, which can produce noticeable overhead in some operations, typically those used with these
basic value types, like mathematics.
The programmer is free to choose which semantics are more appropriate for each data structure in the
application. Larger structures like windows would be defined as classes, allowing them to be passed
around as pointers. Smaller structures, like a 2D point, can be defined as structs, which will be pass-by-
value and allow direct access to their internal data with no dereference. The performance improvement
inherent to the pass-by-value concept is such that Swift uses these types for almost all common data
types, including Int and Double, and types normally represented by objects, like String and Array. Using
value types can result in significant performance improvements in user applications as well.
Protocol-oriented programming:
A key feature of Objective-C is its support for categories, methods that can be added to extend classes
at runtime. Categories allow extending classes in-place to add new functions with no need to subclass
or even have access to the original source code. An example might be to add spell checker support to
the base NSString class, which means all instances of NSString in the application gain spell checking.
The system is also widely used as an organizational technique, allowing related code to be gathered into
library-like extensions. Swift continues to support this concept, although they are now termed
extensions, and declared with the keyword extension. Unlike Objective-C, Swift can also add new
properties accessors, types and enums to extant instances.
Another key feature of Objective-C is its use of protocols, known in most modern languages as
interfaces. Protocols promise that a particular class implements a set of methods, meaning that other
objects in the system can call those methods on any object supporting that protocol. This is often used
in modern OO languages as a substitute for multiple inheritance, although the feature sets are not
entirely similar. A common example of a protocol in Cocoa is the NSCopyingprotocol, which defines
one method, copyWithZone, that implements deep copying on objects
As Swift treats structs and classes as similar concepts, both extensions and protocols are extensively
used in Swift's runtime to provide a rich API based on structs. For instance, Swift uses an extension to
add the Equatable protocol to many of their basic types, like Strings and Arrays, allowing them to be
compared with the == operator. A concrete example of how all of these features interact can be seen in
the concept of default protocol implementations:
func !=<T : Equatable>(lhs: T, rhs: T) -> Bool
This function defines a method that works on any instance conforming to Equatable, providing a not
equals function. Any instance, class or struct, automatically gains this implementation simply by
conforming to Equatable. As many instances gain Equatable through their base implementations or
other generic extensions, most basic objects in the runtime gain equals and not equals with no code
Swift uses the same runtime as the extant Objective-C system, but requires iOS 7 or macOS 10.9 or
higher. Swift and Objective-C code can be used in one program, and by extension, C and C++ also. In
contrast to C, C++ code cannot be used directly from Swift. An Objective-C or C wrapper must be
created between Swift and C++. In the case of Objective-C, Swift has considerable access to the object
CSPIT(CE) 82 | P a g e
CE373 D17CE144
model, and can be used to subclass, extend and use Objective-C code to provide protocol support The
converse is not true: a Swift class cannot be subclassed in Objective-C
Swift also has limited support for attributes, metadata that is read by the development environment, and
is not necessarily part of the compiled code. Like Objective-C, attributes use the @ syntax, but the
currently available set is small. One example is the @IBOutlet attribute, which marks a given value in
the code as an outlet, available for use within Interface Builder (IB). An outlet is a device that binds the
value of the on-screen display to an object in code.
Memory management:
Swift uses Automatic Reference Counting (ARC) to manage memory. Apple used to require manual
memory management in Objective-C, but introduced ARC in 2011 to allow for easier memory
allocation and deallocation One problem with ARC is the possibility of creating a strong reference
cycle, where objects reference each other in a way that you can reach the object you started from by
following references (e.g. A references B, B references A). This causes them to become leaked into
memory as they are never released. Swift provides the keywords weak and unowned to prevent strong
reference cycles. Typically a parent-child relationship would use a strong reference while a child-parent
would use either weak reference, where parents and children can be unrelated, or unowned where a
child always has a parent, but parent may not have a child. Weak references must be optional variables,
since they can change and become nil
A closure within a class can also create a strong reference cycle by capturing self references. Self
references to be treated as weak or unowned can be indicated using a capture list.
A key element of the Swift system is its ability to be cleanly debugged and run within the development
environment, using a read–eval–print loop (REPL), giving it interactive properties more in common
with the scripting abilities of Python than traditional system programming languages. The REPL is
further enhanced with the new concept playgrounds. These are interactive views running within the
Xcode environment that respond to code or debugger changes on-the-fly.Playgrounds allow
programmers to add in Swift code along with markdown documentation. If some code changes over
time or with regard to some other ranged input value, the view can be used with the Timeline Assistant
to demonstrate the output in an animated way. In addition, Xcode has debugging features for Swift
development including breakpoints, step through and step over statements, as well as UI element
placement breakdowns for app developers.
Apple says that Swift "is the first industrial-quality systems programming language that is as expressive
and enjoyable as a scripting language".
Performance:
Many of the features introduced with Swift also have well-known performance and safety trade-offs.
Apple has implemented optimizations that reduce this overhead.
iOS SDK:
In general, a software development kit (SDK) consists of tools used for developing applications for a
particular platform. An SDK includes an application programming interface (API), which serves as a
link between software applications and the platform they run on. APIs can be built in many ways and
include helpful programming libraries and other tools.
CSPIT(CE) 83 | P a g e
CE373 D17CE144
Software development kits may be licensed by the software provider. They are typically made to assist
with platform-specific development that goes on outside of a given company, for example, when
individual developers submit applications or tools to be used with a particular platform.
The iOS SDK dates back to 2007 when Steve Jobs announced the development of this resource in 2008.
The iPhone SDK provides tools for Apple's touchscreen interface and for its proprietary iOS operating
system, which is used to run Apple's iPhones as well as Apple's other mobile devices such as the iPad.
The SDK also contains an iPhone simulator, a program used to simulate the look and feel of iPhone on
the developer's computer. New SDK versions accompany new iOS versions.
Programming languauges:
The iOS SDK, combined with Xcode, helps developers write iOS applications using officially
supported programming languages, including Swift and Objective-C.
● JAVA
● .NET
● Flash
App design
Adaptivity and Layout:
People generally want to be able to use their favorite apps on all of their devices and in any context. In
iOS, interface elements and layouts can be configured to automatically change shape and size on
different devices, during multitasking on iPad, in split view, when the screen is rotated, and more. It’s
essential that you design an adaptable interface that provides a great experience in any environment.
CSPIT(CE) 84 | P a g e
CE373 D17CE144
Auto Layout:
Auto Layout is a development tool for constructing adaptive interfaces. Using Auto Layout, you can
define rules (known as constraints) that govern the content in your app. For example, you can constrain
a button so it’s always horizontally centered and positioned 8 points below an image, regardless of the
available screen space.You can set your app to dynamically adapt to a wide range of traits, including:
● Different device screen sizes, resolutions, and color gamuts (sRGB/P3)
● Different device orientations (portrait/landscape)
● Split view
● Multitasking modes on iPad
● Dynamic Type text-size changes
● Internationalization features that are enabled based on locale (left-to-right/right-to-left layout
direction, date/time/number formatting, font variation, text length)
● System feature availability (3D Touch)
Layout Guides and Safe Area:
Layout guides define rectangular regions that don’t actually appear visibly onscreen, but aid with the
positioning, alignment, and spacing of content. The system includes predefined layout guides that make
it easy to apply standard margins around content and restrict the width of text for
Size Classes:
Size classes are traits that are automatically assigned to content areas based on their size. The system
defines two size classes, regular (denotes expansive space) and compact (denotes constrained space),
which describe the height and width of a view.A view may possess any combination of size classes:
● Regular width, regular height
● Compact width, compact height
● Regular width, compact height
● Compact width, regular height
As with other environmental variations, iOS dynamically makes layout adjustments based on the size
classes of a content area. For example, when the vertical size class changes from compact height to
regular height, perhaps because the user rotated the device from landscape to portrait orientation, tab
bars may become taller.
Conclusion:
Before developing any application first you need to learn basic of the system, its theory and simple uses
like layout, desing rules, coding standards, its IDE tool etc.
CSPIT(CE) 85 | P a g e
CE373 D17CE144
Practical 11
AIM: GoodAsOldPhones I& LoveTweet implementation using swift.
System Requirement: Xcode, swift
Knowledge Requirement: GoodAsOldPhones I& LoveTweet
CODE:
AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
CSPIT(CE) 86 | P a g e
CE373 D17CE144
Product.swift
import Foundation
class Product {
var name: String?
var cellImageName: String?
var fullscreenImageName: String?
init(name: String, cellImageName: String, fullscreenImageName: String) {
self.name = name
self.cellImageName = cellImageName
self.fullscreenImageName = fullscreenImageName
}
}
ProductViewController.swift
import UIKit
class ProductViewController: UIViewController {
@IBOutlet var productImageView: UIImageView!
@IBOutlet var productNameLabel: UILabel!
var product: Product?
override func viewDidLoad() {
super.viewDidLoad()
productNameLabel.text = product?.name
if let imageName = product?.fullscreenImageName {
productImageView.image = UIImage(named: imageName) }
}
@IBAction func addToCartButtonDidTap(_ sender: AnyObject) {
print("Add to cart successfully")
}}
ProductTableViewController.swift
import UIKit
class ProductsTableViewController: UITableViewController {
fileprivate var products: [Product]?
fileprivate let identifer = "productCell"
override func viewDidLoad() {
super.viewDidLoad()
products = [
Product(name: "1907 Wall Set", cellImageName: "image-cell1", fullscreenImageName: "phone-
fullscreen1"),
CSPIT(CE) 87 | P a g e
CE373 D17CE144
CSPIT(CE) 88 | P a g e
CE373 D17CE144
CSPIT(CE) 89 | P a g e
CE373 D17CE144
Practical 12
AIM: Implementation of Stopwatch, To Do List in IoS.
System Requirement: Xcode, swift
Knowledge Requirement: list
Stopwatch:
CODE:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true }
func applicationWillResignActive(_ application: UIApplication) { }
func applicationDidEnterBackground(_ application: UIApplication) { }
func applicationWillEnterForeground(_ application: UIApplication) { }
func applicationDidBecomeActive(_ application: UIApplication) { }
func applicationWillTerminate(_ application: UIApplication) { }-}
ViewController.swift:
import UIKit
class ViewController: UIViewController {
var counter = 0.0
var timer = Timer()
var isPlaying = false
@IBOutlet var Timelabel: UILabel!
@IBOutlet var startbtn: UIButton!
@IBOutlet var pausebtn: UIButton!
@IBOutlet var resetbtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
Timelabel.text = String(counter)
pausebtn.isEnabled = false }
@IBAction func startTimer(_ sender: Any) {
if(isPlaying){
return }
CSPIT(CE) 90 | P a g e
CE373 D17CE144
startbtn.isEnabled = false
pausebtn.isEnabled = true
timer = Timer.scheduledTimer(timeInterval:
0.1,target:self,selector:#selector(UpdateTimer),userInfo:nil, repeats:true)
isPlaying = true
}
@IBAction func pauseTimer(_ sender: Any) {
startbtn.isEnabled = true
pausebtn.isEnabled = false
timer.invalidate()
isPlaying = false
}
@IBAction func resetTimer(_ sender: Any) {
startbtn.isEnabled = true
pausebtn.isEnabled = false
timer.invalidate()
isPlaying = false
counter = 0.0
Timelabel.text = String(counter)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func UpdateTimer() {
counter = counter + 0.1
Timelabel.text = String(format: "%.1f", counter) }
}
OUTPUT:
CSPIT(CE) 91 | P a g e
CE373 D17CE144
TODO LIST:
AppDelegate.swift
// ToDoList
// Created by Apple-05 on 9/17/18.
// Copyright © 2018 Apple-05. All rights reserved.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true }
func applicationWillResignActive(_ application: UIApplication) {
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
CSPIT(CE) 92 | P a g e
CE373 D17CE144
// Called as part of the transition from the background to the active state; here you can undo
many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the
application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also
applicationDidEnterBackground:.
}
}
FirstViewController.swift:
// ToDoList
// Created by Apple-05 on 9/17/18.
// Copyright © 2018 Apple-05. All rights reserved.
import UIKit
var list = ["Buy iphone","Eat Pizza","Play Games","Do Coding","Sleep is must"]
class FirstViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
@IBOutlet var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
myTableView.reloadData()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return(list.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = list[indexPath.row]
CSPIT(CE) 93 | P a g e
CE373 D17CE144
return(cell)
}
public func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle==UITableViewCellEditingStyle.delete{
//self.list.remove(at : indexPath.row)
list.remove(at: indexPath.row)
myTableView.reloadData()
}
}}
SecondViewController.swift:
// ToDoList
// Created by Apple-05 on 9/17/18.
// Copyright © 2018 Apple-05. All rights reserved.
import UIKit
class SecondViewController: UIViewController {
@IBOutlet var input: UITextField!
@IBAction func addItem(_ sender: Any) {
if(input.text != ""){
list.append(input.text!)
input.text=""
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
OUTPUT:
CSPIT(CE) 94 | P a g e
CE373 D17CE144
CSPIT(CE) 95 | P a g e
CE373 D17CE144
Conclusion: Todo list can be made using list feature available in IOS.
CSPIT(CE) 96 | P a g e
CE373 D17CE144
Practical 13
AIM: Create Gallery in iOS.
System Requirement: Xcode, swift
Knowledge Requirement: galary
CODE:
AppDelegate.swift:
// Created by Apple-09 on 8/20/18.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for
certain types of temporary interruptions (such as an incoming phone call or SMS message) or when
the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering
callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough
application state information to restore your application to its current state in case it is terminated
later.
// If your application supports background execution, this method is called instead of
applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo
many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the
application was previously in the background, optionally refresh the user interface.
}
CSPIT(CE) 97 | P a g e
CE373 D17CE144
ViewController.swift:
import UIKit
class ViewController: UIViewController {
@IBOutlet var image: UIImageView!
@IBOutlet var nextBtn: UIButton!
@IBOutlet var label: UILabel!
@IBOutlet var prevBtn: UIButton!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onNext(_ sender: Any)
{
if(imageInt == 3)
{
nextBtn.isEnabled = false
}
else{
prevBtn.isEnabled = true
imageInt = imageInt + 1;
setImage()
}
}
@IBAction func onPrev(_ sender: Any)
{
if(imageInt == 0)
{
prevBtn.isEnabled = false }
CSPIT(CE) 98 | P a g e
CE373 D17CE144
else{
nextBtn.isEnabled = true
imageInt = imageInt - 1;
setImage()
}
}
}
OUTPUT:
MUSIC APP:
CODE:
AppDelegate.swift:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
CSPIT(CE) 99 | P a g e
CE373 D17CE144
certain types of temporary interruptions (such as an incoming phone call or SMS message) or when
the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering
callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough
application state information to restore your application to its current state in case it is terminated
later.
// If your application supports background execution, this method is called instead of
applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo
many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the
application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also
applicationDidEnterBackground:.
}
}
ViewController.swift:
import UIKit
import AVFoundation
import Foundation
import AVKit
class ViewController: UIViewController {
@IBOutlet var btnvPlay: UIButton!
@IBOutlet var btnvPrev: UIButton!
@IBOutlet var btnvNext: UIButton!
@IBOutlet var btnvRestart: UIButton!
@IBOutlet var btnvPause: UIButton!
var i:Int = 0
CSPIT(CE) 100 | P a g e
CE373 D17CE144
}
}
@IBAction func btnnext(_ sender: Any) {
btnvNext.isEnabled = false
btnvPrev.isEnabled = true
i=i+1
if (i % 2 == 1){
do{
audioPlayer = try AVAudioPlayer (contentsOf: URL(fileURLWithPath:
Bundle.main.path(forResource: "a.mp3", ofType: nil)!))
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
} }catch{
print(error)
}
audioPlayer.play()
}else{
do{
audioPlayer = try AVAudioPlayer (contentsOf: URL(fileURLWithPath:
Bundle.main.path(forResource: "aa.mp3", ofType: nil)!))
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
} }catch{
print(error)
}
}
audioPlayer.play()
}
@IBAction func btnPrev(_ sender: Any) {
btnvNext.isEnabled = true
btnvPrev.isEnabled = false
i=i-1
if (i % 2 == 1){
do{
CSPIT(CE) 102 | P a g e
CE373 D17CE144
} }catch{
print(error)
}
}
audioPlayer.play()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Getting the shared instance of the audio session and setting audio to continue playback when
the screen is locked.
let audioSession1 = AVAudioSession.sharedInstance()
do {
try audioSession1.setCategory(AVAudioSessionCategoryPlayback)
}
catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
return true
CSPIT(CE) 103 | P a g e
CE373 D17CE144
}
@IBAction func btnPlayVideo(_ sender: Any) {
let urlHere = URL(fileURLWithPath:
"/Users/charusatuniversity/Desktop/music/music/Songs/b.mp4")
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: urlHere)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
}
}
OUTPUT:
Conclusion: Music player can be simply made by interfacing buttons in the right way.
CSPIT(CE) 104 | P a g e
CE373 D17CE144
Practical 14
AIM: PhotoTagger, Marslink, ceneDetector, Notification UI, Scale, Weather Extention,
HitList & Birthdays in iOS
System Requirement: Xcode, swift
Knowledge Requirement: PhotoTagger, Marslink, ceneDetector, Notification UI, Scale,
Weather Extention, HitList & Birthdays
Code:
ViewController.swift
import UIKit
import Alamofire
let kAuthorization = ""
class ViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet var takePictureButton: UIButton!
@IBOutlet var imageView: UIImageView!
@IBOutlet var progressView: UIProgressView!
@IBOutlet var activityIndicatorView: UIActivityIndicatorView!
// MARK: - Properties
fileprivate var tags: [String]?
fileprivate var colors: [PhotoColor]?
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
takePictureButton.setTitle("Select Photo", for: UIControlState())
}
}
imageView.image = nil
}
CSPIT(CE) 105 | P a g e
CE373 D17CE144
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowResults" {
guard let controller = segue.destination as? TagsColorsViewController else {
fatalError("Storyboard mis-configuration. Controller is not of expected type
TagsColorsViewController")
}
controller.tags = tags
controller.colors = colors
}
}
// MARK: - IBActions
@IBAction func takePicture(_ sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = false
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.sourceType = UIImagePickerControllerSourceType.camera
} else {
picker.sourceType = .photoLibrary
picker.modalPresentationStyle = .fullScreen
}
// MARK: - UIImagePickerControllerDelegate
extension ViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
CSPIT(CE) 106 | P a g e
CE373 D17CE144
print("Info did not have the required UIImage for the Original Image")
dismiss(animated: true)
return
}
imageView.image = image
takePictureButton.isHidden = true
progressView.progress = 0.0
progressView.isHidden = false
activityIndicatorView.startAnimating()
upload(
image: image,
progressCompletion: { [unowned self] percent in
self.progressView.setProgress(percent, animated: true)
},
completion: { [unowned self] tags, colors in
self.takePictureButton.isHidden = false
self.progressView.isHidden = true
self.activityIndicatorView.stopAnimating()
self.tags = tags
self.colors = colors
dismiss(animated: true)
}
}
extension ViewController {
func upload(image: UIImage,
progressCompletion: @escaping (_ percent: Float) -> Void,
completion: @escaping (_ tags: [String], _ colors: [PhotoColor]) -> Void) {
guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {
CSPIT(CE) 107 | P a g e
CE373 D17CE144
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imageData,
withName: "imagefile",
fileName: "image.jpg",
mimeType: "image/jpeg")
},
with: ImaggaRouter.content,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
progressCompletion(Float(progress.fractionCompleted))
}
upload.validate()
upload.responseJSON { response in
guard response.result.isSuccess else {
print("Error while uploading file: \(response.result.error)")
completion([String](), [PhotoColor]())
return
}
CSPIT(CE) 108 | P a g e
CE373 D17CE144
completion(tags)
CSPIT(CE) 109 | P a g e
CE373 D17CE144
}
}
completion(photoColors)
}
}
CSPIT(CE) 110 | P a g e
CE373 D17CE144
CSPIT(CE) 111 | P a g e
CE373 D17CE144
OUTPUT:
CSPIT(CE) 112 | P a g e
CE373 D17CE144
Practical 20
AIM: Deploying all Apps in Particular App Store/HostingSystem Requirement: None
Software Requirement: None
Knowledge Requirement: Publishing app
Publishing is the general process that makes your Android applications available to users. When you
publish an Android application you perform two main tasks:
This page provides an overview of the process you should follow as you prepare to publish your app.
If you plan to publish on Google Play, you should also read the Google Play launch checklist.
Preparing your application for release is a multi-step process that involves the following tasks:
CSPIT(CE) 113 | P a g e
CE373 D17CE144
If your application depends on external servers or services, you need to be sure they are secure and
production ready.
You may have to perform several other tasks as part of the preparation process. For example, you will
need to get a private key for signing your application. You will also need to create an icon for your
application, and you may want to prepare an End User License Agreement (EULA) to protect your
person, organization, and intellectual property.
When you are finished preparing your application for release you will have a signed .apk file that
you can distribute to users.
To learn how to prepare your application for release, see Preparing for Release in the Dev Guide. This
topic provides step-by-step instructions for configuring and building a release version of your
application.
You can release your Android applications several ways. Usually, you release applications through an
application marketplace such as Google Play, but you can also release applications on your own
website or by sending an application directly to a user.
If you want to distribute your apps to the broadest possible audience, releasing through an app
marketplace such as Google Play is ideal.
Google Play is the premier marketplace for Android apps and is particularly useful if you want to
distribute your applications to a large global audience. However, you can distribute your apps through
any app marketplace you want or you can use multiple marketplaces.
Google Play is a robust publishing platform that helps you publicize, sell, and distribute your Android
applications to users around the world. When you release your applications through Google Play you
have access to a suite of developer tools that let you analyze your sales, identify market trends, and
control who your applications are being distributed to. You also have access to several revenue-
enhancing features such as in-app billing and application licensing. The rich array of tools and
features, coupled with numerous end-user community features, makes Google Play the premier
marketplace for selling and buying Android applications.
Releasing your application on Google Play is a simple process that involves three basic steps:
CSPIT(CE) 114 | P a g e
CE373 D17CE144
Google Play lets you target your application to a worldwide pool of users and devices. By configuring
various Google Play settings, you can choose the countries you want to reach, the listing languages
you want to use, and the price you want to charge in each country. You can also configure listing
details such as the application type, category, and content rating. When you are done configuring
options you can upload your promotional materials and your application as a draft (unpublished)
application.
Publishing the release version of your application.
If you are satisfied that your publishing settings are correctly configured and your uploaded
application is ready to be released to the public, you can simply click Publish in the Play Console and
within minutes your application will be live and available for download around the world.
Fig 20.1: Users can simply click Installwhen you send them an application via email.
The easiest and quickest way to release your application is to send it to a user through email. To do
this, you prepare your application for release and then attach it to an email and send it to a user. When
the user opens your email message on their Android-powered device the Android system will
recognize the APK and display an Install Now button in the email message (see figure 1). Users can
install your application by touching the button.
CSPIT(CE) 115 | P a g e
CE373 D17CE144
Distributing applications through email is convenient if you are sending your application to only a few
trusted users, but it provides few protections from piracy and unauthorized distribution; that is,
anyone you send your application to can simply forward it to someone else.
If you do not want to release your app on a marketplace like Google Play, you can make the app
available for download on your own website or server, including on a private or enterprise server. To
do this, you must first prepare your application for release in the normal way. Then all you need to do
is host the release-ready APK file on your website and provide a download link to users.
When users browse to the download link from their Android-powered devices, the file is downloaded
and Android system automatically starts installing it on the device. However, the installation process
will start automatically only if the user has configured their Settings to allow the installation of apps
from unknown sources.
Although it is relatively easy to release your application on your own website, it can be inefficient.
For example, if you want to monetize your application you will have to process and track all financial
transactions yourself and you will not be able to use Google Play's In-app Billing service to sell in-
app products. In addition, you will not be able to use the Licensing service to help prevent
unauthorized installation and use of your application.
Android protects users from inadvertent download and install of apps from locations other than a first-
party app store, such as Google Play, which is trusted. Android blocks such installs until the user opts
into allowing the installation of apps from other sources. The opt-in process depends on the version of
Android running on the user's device:
Fig 10.2. The Install unknown appssystem settings screen, where users grant permission for a
particular source to install unknown apps.
On devices running Android 8.0 (API level 26) and higher, users must navigate to the Install unknown
apps system settings screen to enable app installations from a particular source.
On devices running Android 7.1.1 (API level 25) and lower, users must either enable the Unknown
sources system setting or allow a single installation of an unknown app.
CSPIT(CE) 116 | P a g e
CE373 D17CE144
On devices running Android 8.0 (API level 26) and higher, users must grant permission to install apps
from a source that isn't a first-party app store. To do so, they must enable the Allow app
installs setting for that source within the Install unknown apps system settings screen. Figure 2
illustrates this process.
Unknown sources
Fig 20.3: The Unknown sourcessetting, which determines whether users can install apps that aren't
downloaded from Google Play.
In order for users to allow the installation of apps from non-first-party sources on devices running
Android 7.1.1 (API level 25) and lower, they should enable the Unknown sources setting
in Settings > Security, as shown in Figure 3.
In either case, users need to make this configuration change before they can download and install
unknown apps onto their devices.
Publishing on ios:
The submission process has become much easier these days. You can now validate and submit an
application using Xcode, for example. First, however, you need to create your application in iTunes
Connect.
Visit iTunes Connect, sign in with your iOS developer account, and click Manage Your Apps on the
right. Click the Add New App in the top left, select iOS App, and fill out the form.
The SKU Number is a unique string that identifies your application. I usually use the application's
bundle identifier.
The last piece of information is the Bundle ID of your application. This means selecting the (wildcard
or explicit) App ID that you created earlier from the drop-down menu.
CSPIT(CE) 117 | P a g e
CE373 D17CE144
The information that you enter in this step can be modified once your application is live in the App
Store. In other words, you can change the price and availability of an application without having to
submit an update. You can easily do this by selecting the Pricing and Availability tab on the left of
your app's iTunes Connect page.
CSPIT(CE) 118 | P a g e
CE373 D17CE144
Step 3: Metadata
We've already covered the application's metadata. The only aspect that I haven't talked about yet is
your application's rating. Based on your application's content and functionality, it is given a rating.
This rating is not only useful for telling users about your application's content and features, but is also
used by the operating system for the parental controls features.
It is strongly recommended that you don't try to outsmart the rating system. Apple is well aware of
this strategy and will reject your application if it doesn't agree with the rating that you have set. There
are many other things here that you may need to adjust based on your app, but we won't go over them
since they are pretty self-explanatory. To do this, go to the App Information tab in the left pane.
To submit your app, you need to create an archive. You can only create an archive by building your
application on a generic device. If you select the iOS Simulator in the active scheme, you will notice
CSPIT(CE) 119 | P a g e
CE373 D17CE144
that the Archive option in Xcode's Product menu is grayed out. Connect an iOS device to your Mac,
select it in the active scheme, and select Archive from Xcode's Product menu.
If all went well, you should now have an archive, and Xcode's Organizer should automatically open
and show you the archive you just created.
Select the archive from the list and click the Upload to App Store... button on the right. The
application binary is then uploaded to Apple's servers.
During this process, your application is also validated. If an error occurs during the validation, the
submission process will fail. The validation process is very useful as it will tell you if there is
something wrong with your application binary that would otherwise result in a rejection by the App
Store review team.
6. Waiting
If the submission process went without problems, your application's status will change to Waiting for
Review. It takes several days for Apple to review your app, and the time it takes tends to fluctuate
over time
Conclusion: All you need is one purchased account and an app to publish your app.
CSPIT(CE) 120 | P a g e