Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MAD Practicals

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 120

CE373 D17CE144

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

STEP 1: DOWNLOAD AND INSTALL THE JAVA RUNTIME ENVIRONMENT (JRE)


You can find the download file here:
http://www.oracle.com/technetwork/java/javase/downloads/jre-6u25-download-346243.html.

Fig 1.1: Download

STEP 2: DOWNLOAD AND INSTALL THE JAVA DEVELOPMENT KIT.


On some Windows systems, the launcher script does not find where the JDK is installed. If you
encounter this problem, you need to set an environment variable indicating the correct location.
Select Start menu > Computer > System Properties > Advanced System Properties. Then open
Advanced tab > Environment Variables and add a new system variable
JAVA_HOME that points to your JDK folder, for example
C:\Program
Files\Java\jdk1.7.0_21.

STEP 3: DOWNLOAD ANDROID STUDIO

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

Fig 1.2: Download Android studio

STEP 4: ADDING SDK PACKAGES

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:

• In Android Studio, click SDK Manager in the toolbar.


• If you're not using Android Studio: o Windows: Double-click the SDK Manager.exe file at
the root of the Android SDK directory.
o Mac/Linux: Open a terminal and tools/ directory in the location where the
navigate to the Android SDK
was installed, then execute android sdk.
When you open the SDK Manager for the first time, several packages are selected by default. Leave
these selected, but be sure you have everything you need to get started by following these steps:
Get the latest SDK tools

CSPIT(CE) 2|Page
CE373 D17CE144

Fig 1.3: Android SDK Manger

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

Get the support library for additional APIs


The support library is required for:
• Android Wear
• Android TV
• Google Cast
It also provides these popular APIs:
• Navigation drawer
• Swipe views
• Backward-compatible action bar
• The Android Support Library provides an extended set of APIs that are compatible with most
versions of Android.
Open the Extras directory and select:
• Android Support Repository
• Android Support Library

Get Google Play services for even more APIs


The Google Play services APIs provide a variety of features and services for your Android apps,
such as:
• User authentication
• Google Maps
• Google Cast
• Games achievements and leaderboards
• And much more
To develop with Google APIs, you need the Google Play services package:
Open the Extras directory and select:
 Google Repository
• Google Play services

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.

INSTALL THE PACKAGES


Once you've selected all the desired packages, continue to install:
1. Click Install X packages.
2. In the next window, double-click each package name on the left to accept the license agreement for
each.
3. Click Install.
The download progress is shown at the bottom of the SDK Manager window. Do not exit the SDK
Manager or it will cancel the download.

STEP 5: ANDROID PROJECT VIEW

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.

Fig 1.4: Show the Android Project View.

CSPIT(CE) 4|Page
CE373 D17CE144

Fig 1.5: Show Project Build Files.

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.

 Android Virtual Device (AVD) Manager


AVD Manager has updated screens with links to help you select the most popular device
configurations, screen sizes and resolutions for your app previews.

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.

 Android Activity Lifecycle


Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android
Activity is the subclass of ContextThemeWrapper class.
An activity is the single screen in android. It is like window or frame of Java.
By the help of activity, you can place all your UI components or widgets in a single screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.

CSPIT(CE) 5|Page
CE373 D17CE144

 Android Activity Lifecycle methods

Let's see the 7 lifecycle methods of android activity.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.

CSPIT(CE) 6|Page
CE373 D17CE144

Fig 1.6: Android Activity LifeCycle

Conclusion: Android is very well definded language.

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

Software Required: Android Studio


Knowledge Required: Basic of running Android studio and Emulator

Activity_main.xml:

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


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

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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:

AIM: 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.

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;

public class MainActivity extends Activity


{
Button bt1;
EditText et1,et2;

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

CSPIT(CE) 10 | P a g e
CE373 D17CE144

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


et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);

bt1.setOnClickListener(new View.OnClickListener()
{

@Override public void onClick(View arg0)


{
// TODO Auto-generated method stub

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();
}
}
});

@Override public boolean onCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override public boolean onOptionsItemSelected(MenuItem item)


{
int id = item.getItemId();

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;

public class MainActivity2 extends Activity


{
@Override protected void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
}

@Override public boolean onCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true;
}

@Override public boolean onOptionsItemSelected(MenuItem item)


{
int id = item.getItemId();

if (id == R.id.action_settings)
{
return true;
}

CSPIT(CE) 12 | P a g e
CE373 D17CE144

return super.onOptionsItemSelected(item);
}
}
Output:

Conclusion: Android programs are running succesfully on emulator.

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

Software Required: Android Studio


Knowledge Required: Static parameters

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;

public class MainActivity extends Activity


{
EditText et1,et2;
Button b1;

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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();

if(s1.equals("admin") && s2.equals("admin"))


{
Intent i= new Intent("android.intent.action.VIEW");
i.setData(Uri.parse("http://www.google.com"));

startActivity(i);
}
}
});
}

@Override public boolean onCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override public boolean onOptionsItemSelected(MenuItem item)


{
return super.onOptionsItemSelected(item);
}
}

CSPIT(CE) 15 | P a g e
CE373 D17CE144

Output:

Conclusion: Form validation can be done using javascript.

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.

Software Required: Android studio


Knowledge Required: resource folder

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;

import android.app.Activity; import


android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

CSPIT(CE) 18 | P a g e
CE373 D17CE144

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity


{
Button b1;
EditText et1;

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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);
}
});
}

@Override public boolean onCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override public boolean onOptionsItemSelected(MenuItem item)


{
int id = item.getItemId();
if (id ==
R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}

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;

public class MainActivity2 extends Activity


{
ListView lv1;
String[] arrayOfItems;

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);

lv1 = (ListView) findViewById(R.id.listView1);

String receiveValue = getIntent().getStringExtra("parameter1");

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()
{

@Override public void onItemClick(AdapterView<?> arg0, View


arg1, int arg2,long arg3)
{
String msg = arrayOfItems[arg2];
Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
}
});

@Override public boolean onCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true;
}

@Override public boolean onOptionsItemSelected(MenuItem item)


{

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;

public class MainActivity extends Activity implements OnItemSelectedListener


{
Integer[] aIDS={ R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four
};

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

Spinner sp = (Spinner) findViewById(R.id.spinner1);


sp.setOnItemSelectedListener(this);
}

@Override public booleanonCreateOptionsMenu(Menu menu)


{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@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();

ImageView ie = (ImageView) findViewById(R.id.imageView1);


ie.setImageResource(aIDS[arg2]);
}
}

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;

public class MainActivity extends Activity


{
View view1;

@Override protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

view1 = (View) findViewById(R.id.mainactivity);


}

@Override 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;

CSPIT(CE) 23 | P a g e
CE373 D17CE144

@override 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.

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

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


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-
auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<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

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


<android.support.design.widget.CoordinatorLayout

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>

<include layout="@layout/content_main2" />

<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;

public class MainActivity extends AppCompatActivity


{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e=findViewById(R.id.editText);
b=findViewById(R.id.button);
t=findViewById(R.id.textView);
c=findViewById(R.id.timer);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int time=Integer.parseInt(e.getText().toString());
//Toast.makeText(MainActivity.this, String.valueOf(time),
Toast.LENGTH_SHORT).show();

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;

public class Main2Activity extends AppCompatActivity {

@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

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


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/relativeLayout">

<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;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener{
Spinner spnr;
ImageView imgmaster;
ArrayAdapter<CharSequence> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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

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


<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-
auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/relativeLayout">

<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

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0"
android:toAlpha="1.0"
android:fillAfter="true"
android:duration="7000"
/>
</set>

res\anim\rotate.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:fromDegrees="0"

android:toDegr
ees="-360"
android:pivotX
="50%"
android:pivotY
="50%"
android:duratio
n="7000" />
</set>

res\anim\scale.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:pivotY="50%"
android:pivotX="50%"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="2.0"
android:toYScale="2.0"
android:duration="7000"
/>

CSPIT(CE) 34 | P a g e
CE373 D17CE144

</set>

res\nim\spin.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:pivotY="50%"
android:pivotX="50%"
android:fromDegrees="0"
android:toDegrees="360"
android:duration="7000"
android:repeatCount="infinite"
/>
</set>

res\nim\translate.xml

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


<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="110"
android:fromY
Delta="190"
android:toXDel
ta="-120"
android:toYDel
ta="0"
android:duratio
n="4000"
android:fillAfte
r="true" />
</set>

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;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener{
Spinner spnr;
ImageView
imgmaster;
ArrayAdapter<CharSequence>
adapter; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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.

Software Required: Android Studio


Knowledge Required: UI

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;

public class MainActivity extends Activity {

Spinner sp1;
int cartype;
Button b1;

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

sp1 = (Spinner) findViewById(R.id.spinner1);


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

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) {

//Storing car index into variable.


cartype = arg2;

@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;

public class MainActivity2 extends Activity {

TextView tvCarName,tvcarDetails;
Gallery gallery;

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

tvCarName = (TextView) findViewById(R.id.textView1);


tvcarDetails = (TextView) findViewById(R.id.textView2);

//=================================================================
====
//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

//=================================================================
====

gallery = (Gallery) findViewById(R.id.gallery1);


gallery.setAdapter(new CustomAdapterForGallery(this,carType+""));

@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};

public CustomAdapterForGallery(Context context,String indx)


{
currentContext = context;
CarIndexInString=indx;
}

public int getCount()


{
if(CarIndexInString.equals("0"))
{
return imagearray1.length;
}
else if(CarIndexInString.equals("1"))
{
return imagearray2.length;
}
else if(CarIndexInString.equals("2"))
{
return imagearray3.length;
}
else
{
return imagearray1.length;
}
}

public Object getItem(int position) {


return position;
}

CSPIT(CE) 43 | P a g e
CE373 D17CE144

public long getItemId(int position) {


return position;
}

public View getView(int position, View convertView, ViewGroup parent)


{
ImageView imgView = new ImageView(currentContext);

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]);
}

imgView.setLayoutParams(new Gallery.LayoutParams(200, 200));


imgView.setScaleType(ImageView.ScaleType.FIT_XY);

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.

Software Required: Android Studio


Knowledge Required: android manifest, sqllite 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:text="Android Call Intent Example"

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:hint="Enter Number to Call"

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:text="Developed By: Adarsh Patel"

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;

public class MainActivity extends Activity {

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) {

//Display message to user that we are calling now...


Toast.makeText(getApplicationContext(),"Calling to " +
et1.getText().toString() + "..." , Toast.LENGTH_LONG).show();

//============================================
// 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;

public class FifteenActivity extends Activity


{
/** @author Y@@D */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

SQLiteDatabase myDB= null;


String TableName = "myTable";

String Data="";

/* Create a Database. */
try
{
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);

/* Create a Table in the Database. */


myDB.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " (Field1 VARCHAR,
Field2 INT(3));");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO " + TableName + " (Field1, Field2)" + " VALUES ('Y@@D',
22);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

CSPIT(CE) 50 | P a g e
CE373 D17CE144

int Column1 = c.getColumnIndex("Field1");


int Column2 = c.getColumnIndex("Field2");

// Check if our result was valid.


c.moveToFirst();
if (c != null)
{
// Loop through all Results
do
{
String Name = c.getString(Column1);
int Age = c.getInt(Column2);
Data =Data +Name+"/"+Age+"\n";
}while(c.moveToNext());
}
TextView tv = new TextView(this);
tv.setBackgroundColor(Color.BLUE);
tv.setTextColor(Color.WHITE);
tv.setText(Data);
setContentView(tv);
}
catch(Exception e)
{
Log.e("Error", "Error", e);
}
finally
{
if (myDB != null)
myDB.close();
}
}
}
--------------------------------------------------------------------

package kmn.Fifteen;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;

public class DropTb extends Activity


{

/** @author Y@@D */


@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

SQLiteDatabase myDB= null;

CSPIT(CE) 51 | P a g e
CE373 D17CE144

String TableName = "myTable";

/**
* 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;

public class MainActivity extends Activity {

TextView tv3;

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

tv3 = (TextView) findViewById(R.id.textView3);

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();

tv3.setText("File Stored at : " + locationToStoreFile);

FileOutputStream fos = new FileOutputStream(new


File(locationToStoreFile));

//==========================================
// 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;

public class MainActivity extends Activity {

MediaPlayer mp1;
TextView tv3;

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

tv3 = (TextView) findViewById(R.id.textView3);

CSPIT(CE) 58 | P a g e
CE373 D17CE144

tv3.setText("Playing : " + Environment.getExternalStorageDirectory().getPath()+


"/media1.mp3" );

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";

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, 1);
}

@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);
}

public boolean insertData(String name,String surname,String marks) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);

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;
}

public Cursor getAllData() {


SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}

public boolean updateData(String id,String name,String surname,String marks) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,id);
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}

public Integer deleteData (String id) {


SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
}

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;

public class MainActivity extends ActionBarActivity {


DatabaseHelper myDb;
EditText editName,editSurname,editMarks ,editTextId;
Button btnAddData;
Button btnviewAll;
Button btnDelete;

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

public void onClick(View v) {


boolean isInserted = myDb.insertData(editName.getText().toString(),
editSurname.getText().toString(),
editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not
Inserted",Toast.LENGTH_LONG).show();
}
}
);
}

public void viewAll() {


btnviewAll.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;
}

StringBuffer buffer = new StringBuffer();


while (res.moveToNext()) {
buffer.append("Id :"+ res.getString(0)+"\n");
buffer.append("Name :"+ res.getString(1)+"\n");
buffer.append("Surname :"+ res.getString(2)+"\n");
buffer.append("Marks :"+ res.getString(3)+"\n\n");
}

// Show all data


showMessage("Data",buffer.toString());
}
}
);
}

public void showMessage(String title,String Message){


AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}

@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.

Software Required: Android Studio


Knowledge Required: retrival of data from sd 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.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;

public class MainActivity extends Activity {

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

// Display read text into textview3


//==========================================
tv3 = (TextView)findViewById(R.id.textView3);
tv3.setText(sb);
}

@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;

public class MainActivity extends Activity {

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;

public class TouchEventExample extends View{

private Paint paint = new Paint();

float x1,x2,y1,y2;

public TouchEventExample(Context context) {


super(context);
// TODO Auto-generated constructor stub

paint.setColor(Color.rgb(250, 50, 50));


}

@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);

canvas.drawText(“Touch and Move to Draw Line”, 80, 50, paint);

canvas.drawText(“Developed By: Adarsh Patel”, 80, 300, 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

AIM: Create an application to send message between two emulators.

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;

public class MainActivity extends Activity {

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:

AIM: Create an application to take picture using native application.

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;

public class Pro22Activity extends Activity implements OnClickListener {


/**
* www.master-gtu.blogspot.com
* pankaj sharma(8460479175),
* chavda vijay(8460420769)
*/

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.

Software Required: Android Studio


Knowledge Required: webview, galleryview, permissions

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;

public class ImageGalleryDemoActivity extends Activity {

private static int RESULT_LOAD_IMAGE = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);


buttonLoadImage.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {

Intent i = new Intent(


Intent.ACTION_PICK,

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

if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK &&


null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,


filePathColumn, null, null, null);
cursor.moveToFirst();

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);


String picturePath = cursor.getString(columnIndex);
cursor.close();

ImageView imageView = (ImageView) findViewById(R.id.imgView);


imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

}
}

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;

public class WebviewActivity extends Activity implements OnClickListener


{
/**
* www.master-gtu.blogspot.com
* pankaj sharma(8460479175),
* chavda vijay(8460420769)
*/

//CREATE WEBVIEW OBJECT


WebView web;

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);

// INTIALIZE WEBVIEW OBJECT


// GIVE PERMISSION INTERNET IN ANDROIDMAINFEST FILE

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();

if(!stringurl.startsWith("http://") &amp;&amp; !stringurl.startsWith("https://") )


stringurl="http://"+stringurl;

//ENABELING JAVA SCRIPT ON WEBVIEW


web.getSettings().setJavaScriptEnabled(true);

//LOAD URL ON WEBVIEW


web.loadUrl(stringurl);

//SETTING WEBVIEW CLIENT TO OPEN IN SAME SCREEN NOT ON NATIVE BROWSER


web.setWebViewClient(new WebViewClient());
}
}
}

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]

Optionals and chaining:

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

Libraries, runtime and development:

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.

Debugging and other elements:

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.

Features of iOS SDK:


The iOS SDK is a free download for Mac users. It is not available for Microsoft Windows personal
computers. To test the application, get technical support, and distribute applications through App Store,
developers are required to subscribe to the Apple Developer Program.
The SDK contents are separated into the following sets:

● Cocoa Touch ● Image file formats


● Multi-touch events and controls ● Quartz
● Accelerometer support ● Core Animation
● View hierarchy ● OpenGL ES
● Localization (i18n) ● Core Services
● Camera support ● Networking
● Media ● Embedded SQLite database
● OpenAL ● Core Location
● audio mixing and recording ● Threads
● Video playback ● CoreMotion
● Sockets ● Mac OS X Kernel
● Power management ● TCP/IP
● File system ● Security

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.

General Layout Considerations:


● Ensure that primary content is clear at its default size.
● Maintain an overall consistent appearance throughout your app.
● Use visual weight and balance to convey importance.
● Use alignment to ease scanning and to communicate organization and hierarchy.
● If possible, support both portrait and landscape orientations.
● Provide ample touch targets for interactive elements.
● Preview your app on multiple devices.

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 {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:


[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
ContactViewController.swift
import UIKit
class ContactViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(scrollView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if #available(iOS 11.0, *) {
scrollView.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: view.frame.width, height:
view.frame.height - view.safeAreaInsets.bottom - view.safeAreaInsets.top)
} else {
scrollView.frame = CGRect(x: 0, y: topLayoutGuide.length, width: view.frame.width, height:
view.frame.height - topLayoutGuide.length - bottomLayoutGuide.length)
}
scrollView.contentSize = CGSize(width: self.view.frame.width, height: 800)
}}

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

Product(name: "1921 Dial Phone", cellImageName: "image-cell2", fullscreenImageName:


"phone-fullscreen2"),
Product(name: "1937 Desk Set", cellImageName: "image-cell3", fullscreenImageName: "phone-
fullscreen3"),
Product(name: "1984 Moto Portable", cellImageName: "image-cell4", fullscreenImageName:
"phone-fullscreen4")
]
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return products?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifer, for: indexPath)
guard let products = products else { return cell }
cell.textLabel?.text = products[(indexPath as NSIndexPath).row].name
if let imageName = products[(indexPath as NSIndexPath).row].cellImageName {
cell.imageView?.image = UIImage(named: imageName)
}
return cell;
}
// MARK: - View Transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showProduct" {
if let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell),
let productVC = segue.destination as? ProductViewController {
productVC.product = products?[(indexPath as NSIndexPath).row]
} } }}
OUTPUT:

CSPIT(CE) 88 | P a g e
CE373 D17CE144

Conclusion: I learned to develop basic apps using xcode.

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

func applicationWillTerminate(_ application: UIApplication) {


// Called when the application is about to terminate. Save data if appropriate. See also
applicationDidEnterBackground:.
}
}

ViewController.swift:
import UIKit
class ViewController: UIViewController {
@IBOutlet var image: UIImageView!
@IBOutlet var nextBtn: UIButton!
@IBOutlet var label: UILabel!
@IBOutlet var prevBtn: UIButton!

var arr = ["1", "2", "3", "4"]


var imageInt = 0
func setImage()
{
image.image = UIImage(named: arr[imageInt])
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setImage()
prevBtn.isEnabled = false

}
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
}

func applicationWillResignActive(_ application: UIApplication) {


// Sent when the application is about to move from active to inactive state. This can occur for

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

var audioPlayer = AVAudioPlayer()


override func viewDidLoad() {
btnvRestart.isEnabled = false
btnvPause.isEnabled = false
super.viewDidLoad()
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)
}
}
@IBAction func btnPlay(_ sender: Any) {
audioPlayer.play()
btnvPlay.isEnabled = false
btnvPause.isEnabled = true
btnvRestart.isEnabled = true
}
@IBAction func btnPause(_ sender: Any) {
if audioPlayer.isPlaying{
audioPlayer.pause()
btnvPlay.isEnabled = true
btnvPause.isEnabled = false
}else{
}
}
@IBAction func btnRestart(_ sender: Any) {
btnvRestart.isEnabled = false
btnvPause.isEnabled = false
btnvPlay.isEnabled = true
if audioPlayer.isPlaying{
audioPlayer.currentTime = 0
audioPlayer.play()
}else{
CSPIT(CE) 101 | 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

audioPlayer = try AVAudioPlayer (contentsOf: URL(fileURLWithPath:


Bundle.main.path(forResource: "a.mp3", ofType: nil)!))
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catctch{
} }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()
}
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]?

// MARK: - View Life Cycle


override func viewDidLoad() {
super.viewDidLoad()

if !UIImagePickerController.isSourceTypeAvailable(.camera) {
takePictureButton.setTitle("Select Photo", for: UIControlState())
}
}

override func viewDidDisappear(_ animated: Bool) {


super.viewDidDisappear(animated)

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
}

present(picker, animated: true, completion: nil)


}
}

// MARK: - UIImagePickerControllerDelegate
extension ViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo


info: [String: Any]) {
guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {

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

self.performSegue(withIdentifier: "ShowResults", sender: self)


})

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

print("Could not get JPEG representation of UIImage")


return
}

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
}

guard let responseJSON = response.result.value as? [String: Any],


let uploadedFiles = responseJSON["uploaded"] as? [Any],
let firstFile = uploadedFiles.first as? [String: Any],
let firstFileID = firstFile["id"] as? String else {
print("Invalid information received from service")
completion([String](), [PhotoColor]())
return
}

print("Content uploaded with ID: \(firstFileID)")

CSPIT(CE) 108 | P a g e
CE373 D17CE144

self.downloadTags(contentID: firstFileID) { tags in


self.downloadColors(contentID: firstFileID) { colors in
completion(tags, colors)
}
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
}

func downloadTags(contentID: String, completion: @escaping ([String]) -> Void) {


Alamofire.request(ImaggaRouter.tags(contentID))
.responseJSON { response in

guard response.result.isSuccess else {


print("Error while fetching tags: \(response.result.error)")
completion([String]())
return
}

guard let responseJSON = response.result.value as? [String: Any],


let results = responseJSON["results"] as? [[String: Any]],
let firstObject = results.first,
let tagsAndConfidences = firstObject["tags"] as? [[String: Any]] else {
print("Invalid tag information received from the service")
completion([String]())
return
}

let tags = tagsAndConfidences.flatMap({ dict in


return dict["tag"] as? String
})

completion(tags)

CSPIT(CE) 109 | P a g e
CE373 D17CE144

}
}

func downloadColors(contentID: String, completion: @escaping ([PhotoColor]) -> Void) {


Alamofire.request(ImaggaRouter.colors(contentID))
.responseJSON { response in

guard response.result.isSuccess else {


print("Error while fetching colors: \(response.result.error)")
completion([PhotoColor]())
return
}

guard let responseJSON = response.result.value as? [String: Any],


let results = responseJSON["results"] as? [[String: Any]],
let firstResult = results.first,
let info = firstResult["info"] as? [String: Any],
let imageColors = info["image_colors"] as? [[String: Any]] else {
print("Invalid color information received from service")
completion([PhotoColor]())
return
}

let photoColors = imageColors.flatMap({ (dict) -> PhotoColor? in


guard let r = dict["r"] as? String,
let g = dict["g"] as? String,
let b = dict["b"] as? String,
let closestPaletteColor = dict["closest_palette_color"] as? String else {
return nil
}

return PhotoColor(red: Int(r), green: Int(g), blue: Int(b), colorName: closestPaletteColor)


})

completion(photoColors)
}
}

CSPIT(CE) 110 | P a g e
CE373 D17CE144

CSPIT(CE) 111 | P a g e
CE373 D17CE144

OUTPUT:

Conclusion: Photo Tagger is available in IOS.

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

Publish your app (Android)

Publishing is the general process that makes your Android applications available to users. When you
publish an Android application you perform two main tasks:

 You prepare the application for release.


During the preparation step you build a release version of your application, which users can download
and install on their Android-powered devices.
 You release the application to users.
During the release step you publicize, sell, and distribute the release version of your application to
users.

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 app for release

Preparing your application for release is a multi-step process that involves the following tasks:

 Configuring your application for release.


At a minimum you need to remove Log calls and remove the android:debuggable attribute from your
manifest file. You should also provide values for
the android:versionCode and android:versionName attributes, which are located in
the <manifest> element. You may also have to configure several other settings to meet Google Play
requirements or accommodate whatever method you're using to release your application.
If you are using Gradle build files, you can use the release build type to set your build settings for the
published version of your app.
 Building and signing a release version of your application.
You can use the Gradle build files with the release build type to build and sign a release version of
your application. See Building and Running from Android Studio.
 Testing the release version of your application.
Before you distribute your application, you should thoroughly test the release version on at least one
target handset device and one target tablet device.
 Updating application resources for release.
You need to be sure that all application resources such as multimedia files and graphics are updated
and included with your application or staged on the proper production servers.
 Preparing remote servers and services that your application depends on.

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.

Releasing your app to users

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.

Releasing through an app marketplace

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.

Releasing your apps on Google Play

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:

 Preparing promotional materials.


To fully leverage the marketing and publicity capabilities of Google Play, you need to create
promotional materials for your application, such as screenshots, videos, graphics, and promotional
text.
 Configuring options and uploading assets.

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.

For more information, see Google Play.

Releasing your application through email

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.

Releasing through a website

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.

User opt-in for unknown apps and sources

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

Install unknown apps

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.

Step 1: Basic Information


The App Name, which needs to be unique, is the name of your application as it will appear in the
App Store. This can be different than the name that is displayed below your application icon on the
home screen, but it is recommended to choose the same name.

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

Fig 20.4: Name the app

Step 2: Price and Availability


In the next step, you specify your application's price and availability. Apple works with price tiers so
that you don't have to specify a price for each country that Apple operates in. You can also specify in
which stores your application should—or shouldn't—be available.

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

Fig 20.5: Price and availability

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.

5. Uploading the App Binary

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

You might also like