Mobile Application Development

You might also like

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

PRACTICAL FILE

MOBILE APPLICATIONS
DEVELOPMENT

SUBMITTED TO:- SUBMITTED BY:-


JASPREET MA’AM SURAJ KUKRETI
2111934
MCA III

1
INDEX
SNo. Programs Page No.
1. Using emulator to deploy and run mobile apps 3-5

2. Create an Android application that shows Hello + 6 - 11


name of the user and run it on an emulator.

3. Create an application that takes the name from a text 15 - 15


box and shows hello message along with the name
entered in text box, when the user clicks the OK
button.
4. Develop an ANDRIOD application that uses GUI 16 - 19
components, Font and Colors
5. Write an application that draws basic graphical 20 -22
primitives on the screen.
6. Develop an application that uses Layout Managers 23 -27
and event listeners
7. Create and Login application as above. On successful 28 - 30
login, open browser with any URL
8. Testing mobile app - unit testing, black box testing 31 -32
and test automation
9. Create an iOS application that can play audio and 33 - 35
video files
10. Write an iOS application that creates alarm clock 36 -38
11. Devise an iOS application that draws basic graphical 39 - 41
primitives (rectangle, circle) on the screen

12. Build an iOS mobile application that create, save, 42 - 52


update and delete data in a database.

2
Q1. Using emulator to deploy and run mobile apps.

Setting Up the Android Emulator

To use the Android Emulator, you will need to download it first. You can
download it from the SDK manager located in the tools.

Select Tools > SDK Manager. Then, from the settings window, choose Android
Emulator. Click Apply, and Android Studio will download the emulator for you.

Wait for the installations to complete, and then restart your computer and Android
Studio.

Now, select Tools >AVD Manager (for Android Virtual Device), and explore
the virtual devices.

When you set out to create a new virtual device, you’ll have to determine its
hardware first. This is where you select settings like the screen size, screen
resolution, screen pixel density, and RAM. You can define the hardware from
scratch or use the default hardware options offered by Android Studio.

In the hardware selection menu, you’ll also get to see a Play Store icon beside
some of the hardware choices. The system image of these devices will have a
Play Store integrated into their interfaces.

Android Studio asks you about the minimum SDK requirements when creating a
new project. These requirements include the API level and the Android version.
3
Recall this information and select the system image accordingly. Select the most
relevant system image, and click Next to download it if it isn’t downloaded
already.

Further customizations take place on the last screen for creating a new virtual
device.

With all the settings in place, you’ve successfully created a new virtual device, and
it should now show up in your AVD manager.

If you want to see how it looks, open the drop-down menu from the Actions
column and select Cold Boot Now. The emulator will show up on your screen.

Running a Sample Project

If you do not have an application to run in the emulator and just want to
experiment with it, Android Studio lets you download and run a sample project.
To import a sample project, open the File menu and select New. In there, you’ll
find an option for importing a sample project.

4
5
Q2. Create an android application that shows Hello +name of the user who
are logged in and run it on an emulator.

CODE:

package com.example.myapplication;

import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import
com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
importcom.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;

importandroidx.annotation.NonNull;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Locale;

import android.widget.Toast;

import com.example.myapplication.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {


// Remove the below line after defining your own ad unit ID.
6
private static final String TOAST_TEXT = "Test ads are being shown. "
+ "To show live ads, replace the ad unit ID in res/values/strings.xml with
your own ad unit ID.";
private static final String TAG = "MainActivity";

private static final int START_LEVEL =


1; private int mLevel;
private Button mNextLevelButton;
private InterstitialAdmInterstitialAd;
private TextViewmLevelTextView;
private ActivityMainBinding
binding;

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

binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());

MobileAds.initialize(this, new OnInitializationCompleteListener() {


@Override
public void
onInitializationComplete(InitializationStatusinitializationStatus) {
}
});

// Load the InterstitialAd and set the adUnitId (defined in values/strings.xml).


loadInterstitialAd();

// Create the next level button, which tries to show an interstitial when
clicked.
mNextLevelButton = binding.nextLevelButton;
mNextLevelButton.setEnabled(false);
mNextLevelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{ showInterstitial();
7
}

8
});

// Create the text view to show the level


number. mLevelTextView = binding.level;
mLevel = START_LEVEL;

// Toasts the test ad message on the screen. Remove this after defining your
own ad unit ID.
Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
}

@Override
public booleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public booleanonOptionsItemSelected(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);
}

public void loadInterstitialAd() {


AdRequestadRequest = new AdRequest.Builder().build();
InterstitialAd.load(this, getString(R.string.interstitial_ad_unit_id), adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAdinterstitialAd) {
9
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
mNextLevelButton.setEnabled(true);

Toast.makeText(MainActivity.this, "onAdLoaded()",
Toast.LENGTH_SHORT).show();
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback()
{ @Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
mInterstitialAd = null;
Log.d(TAG, "The ad was dismissed.");
}

@Override
public void
onAdFailedToShowFullScreenContent(AdErroradError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
mInterstitialAd = null;
Log.d(TAG, "The ad failed to show.");
}

@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(TAG, "The ad was shown.");
}
});
}

@Override
public void onAdFailedToLoad(@NonNull
10
LoadAdErrorloadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mInterstitialAd = null;
mNextLevelButton.setEnabled(true);

String error = String.format(


Locale.ENGLISH,
"domain: %s, code: %d, message:
%s", loadAdError.getDomain(),
loadAdError.getCode(),
loadAdError.getMessage());
Toast.makeText( MainActivit
y.this,
"onAdFailedToLoad() with error: " +
error, Toast.LENGTH_SHORT)
.show();
}
});
}

private void showInterstitial() {


// Show the ad if it"s ready. Otherwise toast and reload the ad.
if (mInterstitialAd != null) {
mInterstitialAd.show(this);
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
goToNextLevel();
}
}

private void goToNextLevel() {


// Show the next level and reload the ad to prepare for the level after.
mLevelTextView.setText("Level " + (++mLevel));
if (mInterstitialAd == null)
{ loadInterstitialAd();
}

11
}
}

OUTPUT:-

12
Q3. Create an application that takes the name from a text box and shows hello
message along with the name entered in text box, when the user clicks the OK
button.

CODE:

Add button and a text field to the app

To start with, lets open the layout file(content_hello.xml) and click on the design
tab.

From the left palette, click and drag a button and a Text field (EditText) on to the
smartphone.

User would be entering a name in the Text filed..lets click on it and modify the
display text to “Enter Name”.

Similarly, modify the button text to “Click Me”.

Now, select the button and open the Properties window. Modify the onClick
property and provide a method name that will be called when the button is clicked.

At this point, if you switch to the Text tab, the layout file content_hello.xml would
contain code similar to this :

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

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

app:layout_behavior="@string/appbar_scrolling_view_behavior"

13
tools:context="com.topjavatutorial.helloworldapp.HelloActivity"

tools:showIn="@layout/activity_hello">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"

android:id="@+id/textView" />

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:inputType="textPersonName"

android:text="Enter Name"

android:ems="10"

android:id="@+id/editText"

android:layout_below="@+id/textView"

android:layout_centerHorizontal="true"

android:layout_marginTop="57dp" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:id="@+id/button"
14
android:layout_below="@+id/editText"

android:layout_toRightOf="@+id/textView"

android:layout_toEndOf="@+id/textView"

android:layout_marginTop="104dp"

android:onClick="doSomething" />

</RelativeLayout>

define the method doSomething() in the Activity class HelloActivity.java.

public void doSomething(View v){

final TextViewoutputText = (TextView) findViewById(R.id.textView);

final EditTextnameText = (EditText) findViewById(R.id.editText);

Button b = (Button)findViewById(R.id.button);

b.setOnClickListener(new View.OnClickListener()

{ public void onClick(View v) {

outputText.setText("Hello " + nameText.getText());

});

15
OUTPUT:

16
Q4. Develop an ANDRIOD application that uses GUI components, Font and
Colors.

Creating a New project:

 Open Android Stdio and then click on File -> New -> New project.

Then type the Application name as “ex.no.1″ and click Next.

Then select the Empty Activity and click Next.

Designing layout for the Android Application:

 Click on app -> res -> layout -> activity_main.xml.


 Code for Activity_main.xml:
?
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent">
6
7 <TextView
8 android:id="@+id/textView"
9 android:layout_width="match_parent"
10 android:layout_height="wrap_content"
11 android:layout_margin="30dp"
12 android:gravity="center"
13 android:text="Hello World!"
17
14 android:textSize="25sp"
15 android:textStyle="bold" />
16
17
18 <Button
19 android:id="@+id/button1"
20 android:layout_width="match_parent"
21 android:layout_height="wrap_content"
22 android:layout_margin="20dp"
23 android:gravity="center"
24 android:text="Change font size"
25 android:textSize="25sp" />
26 <Button
27 android:id="@+id/button2"
28 android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:gravity="center"
android:text="Change color"
android:textSize="25sp" />
</LinearLayout>

Java Coding for the Android Application:

 Click on app -> java -> com.example.exno1 ->MainActivity.


 Code for MainActivity.java:

1 package com.example.exno1;
2
3 import android.graphics.Color;
4 import android.support.v7.app.AppCompatActivity;
5 import android.os.Bundle;
6 import android.view.View;
7 import android.widget.Button;
8 import android.widget.TextView;
9
10public class MainActivity extends AppCompatActivity
11{
12 int ch=1;
13 float font=30;
14 @Override
15 protected void onCreate(Bundle savedInstanceState)
16 {
18
19
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.activity_main);
19 final TextView t= (TextView) findViewById(R.id.textView);
20 Button b1= (Button) findViewById(R.id.button1);
21 b1.setOnClickListener(new View.OnClickListener() {
22 @Override
23 public void onClick(View v)
24 { t.setTextSize(font);
25 font = font +
26 5; if (font ==
27 50) font = 30;
28 }
29 });
30 Button b2= (Button) findViewById(R.id.button2);
31 b2.setOnClickListener(new View.OnClickListener() {
32 @Override
33 public void onClick(View v)
34 { switch (ch) {
35 case 1:
36 t.setTextColor(Color.RED);
37 break;
38 case 2:
39 t.setTextColor(Color.GREEN);
40 break;
41 case 3:
42 t.setTextColor(Color.BLUE);
43 break;
44 case 4:
45 t.setTextColor(Color.CYAN);
46 break;
47 case 5:
48 t.setTextColor(Color.YELLOW);
49 break;
50 case 6:
t.setTextColor(Color.MAGENTA);
break;
}
ch++;
if (ch ==
7) ch =
1;
}
});
}
20
21
}

OUTPUT:

22
Q5. Write an application that draws basic graphical primitives on the screen.

package com.example.exno4;

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.drawable.BitmapDrawable;

import android.os.Bundle;

import android.widget.ImageView;

public class MainActivity extends Activity

@Override

public void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

23
//Creating a Bitmap

Bitmap bg = Bitmap.createBitmap(720, 1280, Bitmap.Config.ARGB_8888);

//Setting the Bitmap as background for the ImageView

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

i.setBackgroundDrawable(new BitmapDrawable(bg));

//Creating the Canvas Object

Canvas canvas = new

Canvas(bg);

//Creating the Paint Object and set its color&TextSize

Paint paint = new Paint();

paint.setColor(Color.BLUE);

paint.setTextSize(50);

//To draw a Rectangle

canvas.drawText("Rectangle", 420, 150,

paint);

canvas.drawRect(400, 200, 650, 700, paint);

//To draw a Circle

canvas.drawText("Circle", 120, 150,


24
paint);

canvas.drawCircle(200, 350, 150, paint);

25
//To draw a Square

canvas.drawText("Square", 120, 800,

paint);

canvas.drawRect(50, 850, 350, 1150, paint);

//To draw a Line

canvas.drawText("Line", 480, 800,

paint);

canvas.drawLine(520, 850, 520, 1150, paint);

26
Q6. Develop an application that uses Layout Managers and event listeners.

(incomp)

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

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<LinearLayout

android:layout_width="match_parent"

android:layout_height="100dp">

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="30dp"

android:text="Details Form"

android:textSize="25sp"

android:gravity="center"/>

</LinearLayout>

<GridLayout

android:id="@+id/gridLayout"

android:layout_width="match_parent"
27
android:layout_height="match_parent"

android:layout_marginTop="100dp"

android:layout_marginBottom="200dp"

android:columnCount="2"

android:rowCount="3">

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="0"

android:layout_column="0"

android:text="Name"

android:textSize="20sp"

android:gravity="center"/>

<EditText

android:id="@+id/editText"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="0"

android:layout_column="1"

android:ems="10"/>

28
<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="1"

android:layout_column="0"

android:text="Reg.No"

android:textSize="20sp"

android:gravity="center"/>

<EditText

android:id="@+id/editText2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="1"

android:layout_column="1"

android:inputType="number"

android:ems="10"/>

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
29
android:layout_margin="10dp"

android:layout_row="2"

android:layout_column="0"

android:text="Dept"

android:textSize="20sp"

android:gravity="center"/>

<Spinner

android:id="@+id/spinner"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_row="2"

android:layout_column="1"

android:spinnerMode="dropdown"/>

</GridLayout>

<Button

android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:layout_centerInParent="true"

android:layout_marginBottom="150dp"
30
android:text="Submit"/>

</RelativeLayout>

31
Q7. Create and Login application as above. On successful login, open browser
with any URL

CODE:

package ps.pro4;

import android.app.Activity;

import

android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

public class Pro4Activity extends Activity implements OnClickListener {

/**

* www.master-gtu.blogspot.com

* pankajsharma(8460479175),

* chavdavijay(8460420769)

*/

Button btlogin,btclear;

EditTexteditemail,editpass;

@Override

public void onCreate(Bundle savedInstanceState)

{ super.onCreate(savedInstanceState);

32
setContentView(R.layout.main);

33
editemail=(EditText) findViewById(R.id.editemail);

editpass=(EditText) findViewById(R.id.editpass);

btlogin=(Button) findViewById(R.id.btlogin);

btclear=(Button) findViewById(R.id.btclear);

btlogin.setOnClickListener(this);

btclear.setOnClickListener(this);

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

Button action=(Button) v;

if(action.getId()==btlogin.getId())

String email=editemail.getText().toString();

String pass=editpass.getText().toString();

if(email.equals("pankaj@gmail.com") &&pass.equals("pankaj"))

Intent myintent=new
Intent(Intent.ACTION_VIEW,Uri.parse("http://www.gmail.com"));

this.startActivity(myintent);

else

Toast.makeText(this,"Sorry", Toast.LENGTH_SHORT).show();

34
}

else if(action.getId()==btclear.getId())

if(!editemail.getText().toString().equals("") ||
!editpass.getText().toString().equals(""))

editemail.setText("");

editpass.setText("");

else

Toast.makeText(this,"Already Cleared...", Toast.LENGTH_SHORT).show();

35
Q8. Testing mobile app - unit testing, black box testing and test automation.

Black Box Testing is a software testing method in which the functionalities of


software applications are tested without having knowledge of internal code
structure, implementation details and internal paths. Black Box Testing mainly
focuses on input and output of software applications and it is entirely based on
software requirements and specifications. It is also known as Behavioral Testing.

How to do BlackBox Testing

 Initially, the requirements and specifications of the system are examined.


 Tester chooses valid inputs (positive test scenario) to check whether SUT
processes them correctly. Also, some invalid inputs (negative test
scenario) are chosen to verify that the SUT is able to detect them.
 Tester determines expected outputs for all those inputs.
 Software tester constructs test cases with the selected inputs.
 The test cases are executed.
 Software tester compares the actual outputs with the expected outputs.
 Defects if any are fixed and re-tested.

Types of Black Box Testing

 Functional testing – This black box testing type is related to the


functional requirements of a system; it is done by software testers.
 Non-functional testing – This type of black box testing is not related to
testing of specific functionality, but non-functional requirements such
as performance, scalability, usability.
 Regression testing – Regression Testing is done after code fixes, upgrades
or any other system maintenance to check the new code has not affected
the existing code.

Tools used for Black Box Testing:

Tools used for Black box testing largely depends on the type of black box testing
you are doing.

 For Functional/ Regression Tests you can use – QTP, Selenium


 For Non-Functional Tests, you can use- LoadRunner, jmeter

36
Black Box Testing Techniques

 Equivalence Class Testing: It is used to minimize the number of


possible test cases to an optimum level while maintains reasonable test
coverage.
 Boundary Value Testing: Boundary value testing is focused on the values
at boundaries. This technique determines whether a certain range of values
are acceptable by the system or not. It is very useful in reducing the
number of test cases. It is most suitable for the systems where an input is
within certain ranges.
 Decision Table Testing: A decision table puts causes and their effects in
a matrix. There is a unique combination in each column.

37
Q9. Create an Iosapplication that can play audio and video files.

CODE:

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it
“AudioVideo”.

Step 2 − Open Main.storyboard and add three buttons and name them as shown
below.

Step 3 − Create @IBOutlet for three buttons and name it to stop, playButton
and video button, as their name suggests they will be used to play the sound and
stop the sound and playVideo.

Step 4 − We will be using AVFoundation Framework given by apple, The


AVFoundation framework combines four major technology areas that together
encompass a wide range of tasks for capturing, processing, synthesizing,
controlling, importing and exporting audiovisual media on Apple platforms.

Step 5 − Navigate to your project Build Phases and add AVFoundation Framework

Step 6 − In your project directory add the mp3/audio file which you wish to play.

Step 7 − In you ViewController.swift import the framework,

import AVFoundation
38
Step 8 − Create an Object of AVAudioPlayer.

var avPlayer = AVAudioPlayer()

Step 9 − In play button IBAction write the below code.

@IBAction funcplayButton(_ sender: Any) {

guard let url = Bundle.main.url(forResource: "sample", withExtension: "mp3")

else {

return

do {

avPlayer = try AVAudioPlayer(contentsOf:

url) avPlayer.play()

catch {

Step 10 − In stop IBAction write the following

line @IBAction funcstop(_ sender: Any) {

avPlayer.stop()

Step 11 − In video button write the following

code @IBAction funcvideoButton(_ sender: Any)

let path = Bundle.main.path(forResource: "one", ofType: "mp4")

let videoUrl = URL(fileURLWithPath: path!)


39
let player = AVPlayer(url: videoUrl as URL)

40
let playerLayer = AVPlayerLayer(player: player)

playerLayer.frame = self.view.bounds

self.view.layer.addSublayer(playerLayer)

player.play()

Run the application to play audio and video.

41
Q10. Write an iOS application that creates alarm clock.

Create new Single View Application project and name it SingleAlarm.

IndidFinishLaunchingWithOptions method in AppDelegate.m class


registerUIUserNotificationSetting or UIRemoteNotificationType according to the
iOS running in your device.

Open ViewController.hfile; declare three properties with IBOutlets likely


UILabel titled lblAlarm, UIDatePicker titled dataPicker and UISwitch titled
switchAlarm. Declare a method scheduleLocalNotificationWithDate, their use we
will see later in brief way.

In Main.storyboardfile add UIDatePicker and one UIButton titled Set Alarm into
view. Now add one UILabel to show date and time whatever we will set using date
picker. Add one UISwitch to makes scheduled alarm ON or OFF. Connect UI
objects to respective IBOutlet and IBActions as we described above. Check below
screen shots.

OpenViewController.m class and create an instance variable of already declared


properties in ViewController.h class using synthesize. In viewDidLoad method
firstly we will check for any alarm has been already scheduled or not; to check this
we have used NSUserDefaults which we used to store fire date of alarm. So now
what we have to do is populate date picker by setting current date and time using
[NSDatedate] if there are no any scheduled alarm other than populate the stored

42
date into date picker. Create a date formatter to display date and time into Alarm
label, which we took earlier as lblAlarm.

Now we will implement a method to toggle alarm state either you want to keep
alarm ON or OFF. Let’s give this method name alarmSwitch and in this method we
have implemented logic to schedule or cancel alarm using the methods
alarmSetButtonTapped and alarmCancelButtonTapped respectively

We have implemented method declared as alarm SetButtonTapped, which will be


triggered when

User will tap on Set Alarm button located at bottom centre and

User will activate alarm by switching alarm to ON state.

In this method we simply getting time from DatePicker and setting alarm by
scheduling a UILocalNotification through
scheduleLocalNotificationWithDatemethod that you can see coded at last into
below screenshot. The use of scheduleLocalNotificationWithDatemethod is to
schedule a notification by setting a fire date and to store the same date and time
into device memory through NSUserDefaults.

We have also used another properties of UILocalNotification to display message


and play a sound when scheduled notification will invoke. To do such things we
have used notification properties like setAlertBody: to display alarm message and
setSoundName: (Here we used sound clip AlramClock.m4r that we have already
copied into project bundle) to ring up a sound on alarm execution.

We have created alarmCancelButtonTapped to cancel out the scheduled alarm


and to remove the scheduler date from device memory. This method will be
triggered when user toggle alarm switch from ON state to OFF state. In present
Messagemethod is used to give prompt to user when new alarm will be scheduled
or cancelled out.

That’s it! You’re now ready to test your application. Just hit the Run button. If
everything is correct your application should run properly.

43
44
Q11. Devise an iOS application that draws basic graphical primitives
(rectangle, circle) on the screen.

Open eclipse or android studio and create new project


 Select our project in the project explorer
 Go to res folder and select layout Double click the main xml file
 Type the code for main.xml or drag and drop various
components used in our program
 Drag and drop relative layout and change its properties
 Drag and drop image view and change its properties according
to our programs
 Screen layout can be viewed by clicking graphics layout tab
 Include necessary files
 Override OnCreate() function
 Create Image view and initialize its using id of some
components used in the xml program
 Save the program
 Run the program
 Output can be viewed in the android emulator

Code for Activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</RelativeLayout>

Code for MainActivity.java:


package com.example.exno4;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;

45
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity

{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating a Bitmap
Bitmapbg = Bitmap.createBitmap(720,
1280, Bitmap.Config.ARGB_8888);
//Setting the Bitmap as background for the ImageView
ImageViewi = (ImageView) findViewById(R.id.imageView);
i.setBackgroundDrawable(new BitmapDrawable(bg));
//Creating the Canvas Object
Canvas canvas = new
Canvas(bg);
//Creating the Paint Object and set its color&TextSize
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(50);
//To draw a Rectangle
canvas.drawText("Rectangle", 420, 150,
paint);
canvas.drawRect(400, 200, 650, 700, paint);
//To draw a Circle
canvas.drawText("Circle", 120, 150,
paint);

canvas.drawCircle(200, 350, 150, paint);


//To draw a Square
canvas.drawText("Square", 120, 800,
paint);
46
canvas.drawRect(50, 850, 350, 1150, paint);
//To draw a Line
canvas.drawText("Line", 480, 800,
paint);

47
canvas.drawLine(520, 850, 520, 1150, paint);
}

OUTPUT:

48
Q12. Build an iOS mobile application that create, save, update and delete data
in a database.

create a single-view iOS application name it as SQLiteDemo to start with SQLite


operations

Once we are done creating the project, open the Main.storyboard file and add a
table view to the View Controller as shown in the below image.

To use the table view, we also need to create its outlet in the ViewController.swift
class. Once we implement the delegate and datasource methods, the
ViewController.swift contains the following code.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!


49
override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view.

tableView.delegate = self

tableView.dataSource = self

extension ViewController : UITableViewDelegate{

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPat


h) -> CGFloat {

return UITableView.automaticDimension

extension ViewController : UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)


-> Int {

return 5

50
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -
> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") ?? UIT


ableViewCell()

return cell

Now, we will create a model class Employee. In our project, the Employee has the
name, age, and id. For this purpose, create a new swift file and add the following
code.

import Foundation

class Employee

var name: String = ""

var age: Int = 0

var id: Int = 0

init(id:Int, name:String, age:Int)

self.id = id

self.name = name

self.age = age

51
Now, we will create a class that contains the DB operations. We have named the
class as DBManager. It includes the methods to create the database, create the
table, insert in the table, read from the table, and performing the deletion. The
DBManager contains the following code.

import Foundation

import SQLite3

class DBManager

init()

db =

openDatabase()

createTable()

let dbPath: String = "myDb.sqlite"

var db:OpaquePointer?

func openDatabase() -> OpaquePointer?

let filePath = try! FileManager.default.url(for: .documentDirectory, in: .userDomai


nMask, appropriateFor: nil, create: false)

52
.appendingPathComponent(dbPath)

53
var db: OpaquePointer? = nil

if sqlite3_open(filePath.path, &db) != SQLITE_OK

debugPrint("can't open database")

return nil

else

print("Successfully created connection to database at \(dbPath)")

return db

func createTable() {

let createTableString = "CREATE TABLE IF NOT EXISTS person(Id INTEGER


PRIMARY KEY,name TEXT,age INTEGER);"

var createTableStatement: OpaquePointer? = nil

if sqlite3_prepare_v2(db, createTableString, -
1, &createTableStatement, nil) == SQLITE_OK

if sqlite3_step(createTableStatement) == SQLITE_DONE

print("person table created.")

 } else {
 print("person table could not be created.")

}
54
} else {

print("CREATE TABLE statement could not be prepared.")

sqlite3_finalize(createTableStatement)

func insert(id:Int, name:String, age:Int)

let persons = read()

for p in persons

if p.id == id

return

let insertStatementString = "INSERT INTO person (Id, name, age) VALUES (?, ?,
?);"

var insertStatement: OpaquePointer? = nil

if sqlite3_prepare_v2(db, insertStatementString, -
1, &insertStatement, nil) == SQLITE_OK {

sqlite3_bind_int(insertStatement, 1, Int32(id))

sqlite3_bind_text(insertStatement, 2, (name as NSString).utf8String, -1, nil)

sqlite3_bind_int(insertStatement, 3, Int32(age))

55
if sqlite3_step(insertStatement) == SQLITE_DONE {

print("Successfully inserted row.")

} else {

print("Could not insert row.")

} else {

print("INSERT statement could not be prepared.")

sqlite3_finalize(insertStatement)

func read() -> [Employee] {

let queryStatementString = "SELECT * FROM person;"

var queryStatement: OpaquePointer? = nil

var emps : [Employee] = []

if sqlite3_prepare_v2(db, queryStatementString, -
1, &queryStatement, nil) == SQLITE_OK {

while sqlite3_step(queryStatement) == SQLITE_ROW {

let id = sqlite3_column_int(queryStatement, 0)

let name = String(describing: String(cString: sqlite3_column_text(queryStatement,


1)))

let year = sqlite3_column_int(queryStatement, 2)

emps.append(Employee(id: Int(id), name: name, age: Int(year)))

print("Query Result:")

56
print("\(id) | \(name) | \(year)")

} else {

print("SELECT statement could not be prepared")

sqlite3_finalize(queryStatement)

return emps

func deleteByID(id:Int) {

let deleteStatementStirng = "DELETE FROM person WHERE Id = ?;"

var deleteStatement: OpaquePointer? = nil

if sqlite3_prepare_v2(db, deleteStatementStirng, -
1, &deleteStatement, nil) == SQLITE_OK {

sqlite3_bind_int(deleteStatement, 1, Int32(id))

if sqlite3_step(deleteStatement) == SQLITE_DONE {

print("Successfully deleted row.")

} else {

print("Could not delete row.")

} else {

print("DELETE statement could not be prepared")

sqlite3_finalize(deleteStatement)

}
57
}

Finally, we need to save the data in db in the ViewController. For this purpose, we
will use DBManager class to save and retrieve data. The ViewController.swift
contains the following code.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

var db = DBManager()

var emps = Array<Employee>()

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view.

tableView.delegate = self

tableView.dataSource = self

db.insert(id: 1, name: "John", age: 24)

db.insert(id: 2, name: "Mike", age: 25)

db.insert(id: 3, name: "Harsh", age: 23)

db.insert(id: 4, name: "Sachin", age: 44)


58
db.insert(id: 5, name: "Rohit", age: 32)

59
emps = db.read()

extension ViewController : UITableViewDelegate{

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexP


ath) -> CGFloat {

return UITableView.automaticDimension

extension ViewController : UITableViewDataSource{

func tableView(_ tableView: UITableView, numberOfRowsInSection section: I


nt) -> Int {

return emps.count

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath


) > UITableViewCell {

60
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") ??
UITableViewCell()

cell.textLabel?.text = "Id: " + emps[indexPath.row].id.description + ", Name:


" + emps[indexPath.row].name + ", age: " + emps[indexPath.row].age.description

return cell

OUTPUT:

61

You might also like