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 [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
[Link];
import [Link];
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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/[Link] 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)
{ [Link](savedInstanceState);
binding = [Link](getLayoutInflater());
setContentView([Link]());
[Link](this, new OnInitializationCompleteListener() {
@Override
public void
onInitializationComplete(InitializationStatusinitializationStatus) {
}
});
// Load the InterstitialAd and set the adUnitId (defined in values/[Link]).
loadInterstitialAd();
// Create the next level button, which tries to show an interstitial when
clicked.
mNextLevelButton = [Link];
[Link](false);
[Link](new [Link]() {
@Override
public void onClick(View view)
{ showInterstitial();
7
}
8
});
// Create the text view to show the level
number. mLevelTextView = [Link];
mLevel = START_LEVEL;
// Toasts the test ad message on the screen. Remove this after defining your
own ad unit ID.
[Link](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([Link].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 [Link].
int id = [Link]();
if (id == [Link].action_settings)
{ return true;
}
return [Link](item);
}
public void loadInterstitialAd() {
AdRequestadRequest = new [Link]().build();
[Link](this, getString([Link].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;
[Link](true);
[Link]([Link], "onAdLoaded()",
Toast.LENGTH_SHORT).show();
[Link](
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, [Link]());
mInterstitialAd = null;
[Link](true);
String error = [Link](
[Link],
"domain: %s, code: %d, message:
%s", [Link](),
[Link](),
[Link]());
[Link]( MainActivit
[Link],
"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) {
[Link](this);
} else {
[Link](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.
[Link]("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="[Link]
xmlns:app="[Link]
xmlns:tools="[Link]
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="[Link]"
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 [Link].
public void doSomething(View v){
final TextViewoutputText = (TextView) findViewById([Link]);
final EditTextnameText = (EditText) findViewById([Link]);
Button b = (Button)findViewById([Link]);
[Link](new [Link]()
{ public void onClick(View v) {
[Link]("Hello " + [Link]());
});
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 “[Link].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="[Link]
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 -> [Link].exno1 ->MainActivity.
Code for [Link]:
1 package [Link].exno1;
2
3 import [Link];
4 import [Link];
5 import [Link];
6 import [Link];
7 import [Link];
8 import [Link];
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 [Link](savedInstanceState);
18 setContentView([Link].activity_main);
19 final TextView t= (TextView) findViewById([Link]);
20 Button b1= (Button) findViewById([Link].button1);
21 [Link](new [Link]() {
22 @Override
23 public void onClick(View v)
24 { [Link](font);
25 font = font +
26 5; if (font ==
27 50) font = 30;
28 }
29 });
30 Button b2= (Button) findViewById([Link].button2);
31 [Link](new [Link]() {
32 @Override
33 public void onClick(View v)
34 { switch (ch) {
35 case 1:
36 [Link]([Link]);
37 break;
38 case 2:
39 [Link]([Link]);
40 break;
41 case 3:
42 [Link]([Link]);
43 break;
44 case 4:
45 [Link]([Link]);
46 break;
47 case 5:
48 [Link]([Link]);
49 break;
50 case 6:
[Link]([Link]);
break;
}
ch++;
if (ch ==
7) ch =
1;
}
});
}
20
21
}
OUTPUT:
22
Q5. Write an application that draws basic graphical primitives on the screen.
package [Link].exno4;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity
@Override
public void onCreate(Bundle savedInstanceState)
[Link](savedInstanceState);
setContentView([Link].activity_main);
23
//Creating a Bitmap
Bitmap bg = [Link](720, 1280, [Link].ARGB_8888);
//Setting the Bitmap as background for the ImageView
ImageViewi = (ImageView) findViewById([Link]);
[Link](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();
[Link]([Link]);
[Link](50);
//To draw a Rectangle
[Link]("Rectangle", 420, 150,
paint);
[Link](400, 200, 650, 700, paint);
//To draw a Circle
[Link]("Circle", 120, 150,
24
paint);
[Link](200, 350, 150, paint);
25
//To draw a Square
[Link]("Square", 120, 800,
paint);
[Link](50, 850, 350, 1150, paint);
//To draw a Line
[Link]("Line", 480, 800,
paint);
[Link](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="[Link]
xmlns:tools="[Link]
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="[Link]"
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 [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Pro4Activity extends Activity implements OnClickListener {
/**
* [Link]
* pankajsharma(8460479175),
* chavdavijay(8460420769)
*/
Button btlogin,btclear;
EditTexteditemail,editpass;
@Override
public void onCreate(Bundle savedInstanceState)
{ [Link](savedInstanceState);
32
setContentView([Link]);
33
editemail=(EditText) findViewById([Link]);
editpass=(EditText) findViewById([Link]);
btlogin=(Button) findViewById([Link]);
btclear=(Button) findViewById([Link]);
[Link](this);
[Link](this);
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button action=(Button) v;
if([Link]()==[Link]())
String email=[Link]().toString();
String pass=[Link]().toString();
if([Link]("pankaj@[Link]") &&[Link]("pankaj"))
Intent myintent=new
Intent(Intent.ACTION_VIEW,[Link]("[Link]
[Link](myintent);
else
[Link](this,"Sorry", Toast.LENGTH_SHORT).show();
34
}
else if([Link]()==[Link]())
if(![Link]().toString().equals("") ||
![Link]().toString().equals(""))
[Link]("");
[Link]("");
else
[Link](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 [Link] 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 [Link] 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 = [Link](forResource: "sample", withExtension: "mp3")
else {
return
do {
avPlayer = try AVAudioPlayer(contentsOf:
url) [Link]()
catch {
Step 10 − In stop IBAction write the following
line @IBAction funcstop(_ sender: Any) {
[Link]()
Step 11 − In video button write the following
code @IBAction funcvideoButton(_ sender: Any)
let path = [Link](forResource: "one", ofType: "mp4")
let videoUrl = URL(fileURLWithPath: path!)
39
let player = AVPlayer(url: videoUrl as URL)
40
let playerLayer = AVPlayerLayer(player: player)
[Link] = [Link]
[Link](playerLayer)
[Link]()
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 [Link]; 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 [Link] 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 [Link] 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="[Link]
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 [Link]:
package [Link].exno4;
import [Link];
import [Link];
import [Link];
import [Link];
45
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
[Link](savedInstanceState);
setContentView([Link].activity_main);
//Creating a Bitmap
Bitmapbg = [Link](720,
1280, [Link].ARGB_8888);
//Setting the Bitmap as background for the ImageView
ImageViewi = (ImageView) findViewById([Link]);
[Link](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();
[Link]([Link]);
[Link](50);
//To draw a Rectangle
[Link]("Rectangle", 420, 150,
paint);
[Link](400, 200, 650, 700, paint);
//To draw a Circle
[Link]("Circle", 120, 150,
paint);
[Link](200, 350, 150, paint);
//To draw a Square
[Link]("Square", 120, 800,
paint);
46
[Link](50, 850, 350, 1150, paint);
//To draw a Line
[Link]("Line", 480, 800,
paint);
47
[Link](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 [Link] 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 [Link]
class. Once we implement the delegate and datasource methods, the
[Link] contains the following code.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
49
override func viewDidLoad() {
[Link]()
// Do any additional setup after loading the view.
[Link] = self
[Link] = self
extension ViewController : UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPat
h) -> CGFloat {
return [Link]
extension ViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
-> Int {
return 5
50
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -
> UITableViewCell {
let cell = [Link](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)
[Link] = id
[Link] = name
[Link] = 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 = "[Link]"
var db:OpaquePointer?
func openDatabase() -> OpaquePointer?
let filePath = try! [Link](for: .documentDirectory, in: .userDomai
nMask, appropriateFor: nil, create: false)
52
.appendingPathComponent(dbPath)
53
var db: OpaquePointer? = nil
if sqlite3_open([Link], &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 [Link] == 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)
[Link](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 [Link]
contains the following code.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var db = DBManager()
var emps = Array<Employee>()
override func viewDidLoad() {
[Link]()
// Do any additional setup after loading the view.
[Link] = self
[Link] = self
[Link](id: 1, name: "John", age: 24)
[Link](id: 2, name: "Mike", age: 25)
[Link](id: 3, name: "Harsh", age: 23)
[Link](id: 4, name: "Sachin", age: 44)
58
[Link](id: 5, name: "Rohit", age: 32)
59
emps = [Link]()
extension ViewController : UITableViewDelegate{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexP
ath) -> CGFloat {
return [Link]
extension ViewController : UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: I
nt) -> Int {
return [Link]
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath
) > UITableViewCell {
60
let cell = [Link](withIdentifier: "tableViewCell") ??
UITableViewCell()
[Link]?.text = "Id: " + emps[[Link]].[Link] + ", Name:
" + emps[[Link]].name + ", age: " + emps[[Link]].[Link]
return cell
OUTPUT:
61